feat: selectable time ranges with SLA per range #60
No files matched your search
+79
-19
@@ -54,7 +54,7 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
||||
if p != nil && me.Policy == "" {
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p)
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -62,6 +62,8 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
v.Root = buildGroupNodes(data.tree, data.rows)
|
||||
v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0
|
||||
v.CanWrite = writableAnywhere(p, data.tree)
|
||||
v.Range = data.rng.Key
|
||||
v.Ranges = rangeOptions(c, data.rng)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
}
|
||||
@@ -70,24 +72,63 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
|
||||
type monitorData struct {
|
||||
tree groupTree
|
||||
rows []web.MonitorRow
|
||||
byID map[uuid.UUID]store.Monitor
|
||||
hourly map[uuid.UUID][]web.Bucket
|
||||
tree groupTree
|
||||
rows []web.MonitorRow
|
||||
byID map[uuid.UUID]store.Monitor
|
||||
// buckets cover the selected range at its resolution.
|
||||
buckets map[uuid.UUID][]web.Bucket
|
||||
down map[uuid.UUID][]web.Span
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
rng web.TimeRange
|
||||
now time.Time
|
||||
}
|
||||
|
||||
// rangeBuckets loads the selected range for all monitors, or one if
|
||||
// monitor is set.
|
||||
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, monitor *uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
||||
out := map[uuid.UUID][]web.Bucket{}
|
||||
since := now.Add(-rng.Window).Truncate(rng.Bucket)
|
||||
width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds()))
|
||||
if rng.Hourly {
|
||||
rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor})
|
||||
for _, r := range rows {
|
||||
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, MonitorID: monitor})
|
||||
for _, r := range rows {
|
||||
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// slaFor returns m's SLA over the window ending now, not counting time
|
||||
// before the monitor existed.
|
||||
func (d monitorData) slaFor(m store.Monitor, window time.Duration) float64 {
|
||||
from := d.now.Add(-window)
|
||||
if m.CreatedAt.After(from) {
|
||||
from = m.CreatedAt
|
||||
}
|
||||
return web.SLA(d.down[m.ID], from, d.now)
|
||||
}
|
||||
|
||||
// loadMonitorData assembles everything the monitor list shows.
|
||||
func (s *Server) loadMonitorData(ctx context.Context, p *principal) (monitorData, error) {
|
||||
d := monitorData{byID: map[uuid.UUID]store.Monitor{}, hourly: map[uuid.UUID][]web.Bucket{}, regionOf: map[uuid.UUID]store.Region{}}
|
||||
// loadMonitorData assembles everything the monitor list shows for rng.
|
||||
// Incidents are loaded far enough back for every SLA window.
|
||||
func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) {
|
||||
now := time.Now()
|
||||
d := monitorData{
|
||||
byID: map[uuid.UUID]store.Monitor{}, down: map[uuid.UUID][]web.Span{},
|
||||
regionOf: map[uuid.UUID]store.Region{}, rng: rng, now: now,
|
||||
}
|
||||
var (
|
||||
monitors []store.Monitor
|
||||
assigned []store.AllMonitorRegionsRow
|
||||
regions []store.Region
|
||||
latest []store.LatestResultsRow
|
||||
open []store.Incident
|
||||
hourly []store.HourlyBucketsRow
|
||||
spans []store.IncidentsSinceRow
|
||||
)
|
||||
var groups []store.MonitorGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
@@ -110,13 +151,23 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal) (monitorData
|
||||
if open, err = q.OpenIncidents(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{OrgID: p.Org.ID, Bucket: now.Add(-24 * time.Hour).Truncate(time.Hour)})
|
||||
if spans, err = q.IncidentsSince(ctx, ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))); err != nil {
|
||||
return err
|
||||
}
|
||||
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, nil, rng, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
d.tree = newGroupTree(groups)
|
||||
for _, sp := range spans {
|
||||
span := web.Span{Start: sp.StartedAt}
|
||||
if sp.ResolvedAt != nil {
|
||||
span.End = *sp.ResolvedAt
|
||||
}
|
||||
d.down[sp.MonitorID] = append(d.down[sp.MonitorID], span)
|
||||
}
|
||||
for _, r := range regions {
|
||||
d.regionOf[r.ID] = r
|
||||
}
|
||||
@@ -135,9 +186,6 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal) (monitorData
|
||||
for _, i := range open {
|
||||
down[i.MonitorID] = true
|
||||
}
|
||||
for _, h := range hourly {
|
||||
d.hourly[h.MonitorID] = append(d.hourly[h.MonitorID], web.Bucket{Start: h.Bucket, Total: h.Total, OK: h.OkCount, Latency: h.AvgLatencyMs})
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if !canInGroup(p, authz.MonitorsRead, d.tree, m.GroupID) {
|
||||
continue
|
||||
@@ -187,10 +235,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal) (monitorData
|
||||
}
|
||||
row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies)))
|
||||
}
|
||||
if u := web.Uptime(d.hourly[m.ID]); u >= 0 {
|
||||
row.Uptime = web.Percent(u)
|
||||
}
|
||||
row.Bars = web.UptimeBars(d.hourly[m.ID], now, time.Hour, 24, "15:04")
|
||||
row.Uptime = web.SLAText(d.slaFor(m, rng.Window))
|
||||
row.Bars = web.UptimeBars(d.buckets[m.ID], now, rng.Bucket, rng.Bars(), rng.Layout)
|
||||
d.rows = append(d.rows, row)
|
||||
}
|
||||
// Problems first, then by name.
|
||||
@@ -212,7 +258,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
return notFoundPage(c)
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
d, err := s.loadMonitorData(ctx, p)
|
||||
d, err := s.loadMonitorData(ctx, p, web.RangeByKey(c.Query("range")))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -224,7 +270,9 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
v := web.MonitorDetailView{
|
||||
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
|
||||
CanWrite: canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID),
|
||||
Latency: web.Latency(d.hourly[id], 480, 96),
|
||||
Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96),
|
||||
Range: d.rng.Key,
|
||||
Ranges: rangeOptions(c, d.rng),
|
||||
Uptime90: "–",
|
||||
}
|
||||
for _, r := range d.rows {
|
||||
@@ -257,6 +305,9 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
buckets[i] = web.Bucket{Start: b.Bucket, Total: b.Total, OK: b.OkCount}
|
||||
}
|
||||
v.Daily = web.UptimeBars(buckets, now, 24*time.Hour, 90, "2006-01-02")
|
||||
for _, w := range web.SLAWindows {
|
||||
v.SLAs = append(v.SLAs, web.SLAEntry{Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window))})
|
||||
}
|
||||
if u := web.Uptime(buckets); u >= 0 {
|
||||
v.Uptime90 = web.Percent(u)
|
||||
}
|
||||
@@ -427,7 +478,7 @@ func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me w
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := s.loadMonitorData(ctx, p)
|
||||
d, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -633,3 +684,12 @@ func (s *Server) settingsIndex(c *gin.Context) {
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SettingsIndex(s.pageFor(c, "console.nav.settings"), me))
|
||||
}
|
||||
|
||||
// rangeOptions builds the range switcher, keeping the current path.
|
||||
func rangeOptions(c *gin.Context, active web.TimeRange) []web.RangeOption {
|
||||
out := make([]web.RangeOption, len(web.Ranges))
|
||||
for i, r := range web.Ranges {
|
||||
out[i] = web.RangeOption{Key: r.Key, Active: r.Key == active.Key, URL: c.Request.URL.Path + "?range=" + r.Key}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestTimeRangesAndSLA(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("r")+".test", uniq("rng-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two days old, down for six minutes half an hour ago.
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
conn, err := e.dbPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
if _, err := conn.Exec(ctx, `SELECT set_config('app.scope', 'system', false)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `UPDATE monitors SET created_at = $2 WHERE id = $1`, id, now.Add(-48*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at) VALUES ($1, $2, $3, $4)`,
|
||||
org, id, now.Add(-30*time.Minute), now.Add(-24*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = conn.Exec(ctx, `SELECT set_config('app.scope', '', false)`)
|
||||
|
||||
_, _, html := owner.page("/monitors/" + id.String() + "?range=1h")
|
||||
// The monitor is two days old, so 7d and longer cover only those two
|
||||
// days: 6 of 2880 minutes down.
|
||||
for _, want := range []string{">1h<", "90.0%", ">7d<", "99.79%", ">90d<"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("monitor page lacks %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42}
|
||||
for key, n := range bars {
|
||||
st, _, html := owner.page("/?range=" + key)
|
||||
if st != http.StatusOK {
|
||||
t.Errorf("GET /?range=%s = %d", key, st)
|
||||
continue
|
||||
}
|
||||
// The dashboard has one monitor; its chart holds one rect per bar.
|
||||
if got := strings.Count(html, "<rect "); got != n {
|
||||
t.Errorf("range %s shows %d bars, want %d", key, got, n)
|
||||
}
|
||||
}
|
||||
if _, _, html := owner.page("/?range=1h"); !strings.Contains(html, "90.0%") {
|
||||
t.Error("dashboard 1h does not show the 1h SLA")
|
||||
}
|
||||
if _, _, html := owner.page("/?range=24h"); !strings.Contains(html, "99.58") {
|
||||
t.Error("dashboard 24h does not show the 24h SLA (6 of 1440 minutes down)")
|
||||
}
|
||||
|
||||
// A monitor created five minutes ago is measured only since then.
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "New", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatal(body)
|
||||
}
|
||||
if _, _, html := owner.page("/monitors/" + body["id"].(string)); !strings.Contains(html, "100%") {
|
||||
t.Error("new monitor without incidents does not show 100%")
|
||||
}
|
||||
}
|
||||
@@ -194,18 +194,22 @@
|
||||
"monitors.edit": "Monitor bearbeiten",
|
||||
"monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)",
|
||||
"monitors.follow_redirects": "Weiterleitungen folgen",
|
||||
"monitors.history": "Verlauf, letzte {{.Range}}",
|
||||
"monitors.interval": "Intervall (Sekunden)",
|
||||
"monitors.interval_hint": "Mindestens {{.Min}} Sekunden.",
|
||||
"monitors.keyword": "Keyword in der Antwort",
|
||||
"monitors.keyword_absent": "Fehler, wenn das Keyword vorkommt",
|
||||
"monitors.last_24h": "letzte 24 Stunden",
|
||||
"monitors.last_90d": "Letzte 90 Tage",
|
||||
"monitors.latency_24h": "Latenz, letzte 24 Stunden",
|
||||
"monitors.latency": "Durchschnittliche Latenz",
|
||||
"monitors.method": "Methode",
|
||||
"monitors.new": "Neuer Monitor",
|
||||
"monitors.range": "Zeitraum",
|
||||
"monitors.range_note": "SLA und Balken: letzte {{.Range}}",
|
||||
"monitors.recent": "Letzte Checks",
|
||||
"monitors.regions": "Regionen",
|
||||
"monitors.regions_hint": "Geprüft von einem zufälligen Checker jeder gewählten Region. Deine eigenen Regionen stehen oben.",
|
||||
"monitors.sla": "SLA",
|
||||
"monitors.sla_table": "SLA nach Zeitraum",
|
||||
"monitors.target": "Ziel",
|
||||
"monitors.target_hint": "URL für HTTP, host:port für TCP und TLS, Hostname für DNS und ICMP.",
|
||||
"monitors.timeout": "Timeout (ms)",
|
||||
|
||||
@@ -194,18 +194,22 @@
|
||||
"monitors.edit": "Edit monitor",
|
||||
"monitors.expect_status": "Expected status (e.g. 2xx, 301)",
|
||||
"monitors.follow_redirects": "Follow redirects",
|
||||
"monitors.history": "History, last {{.Range}}",
|
||||
"monitors.interval": "Interval (seconds)",
|
||||
"monitors.interval_hint": "At least {{.Min}} seconds.",
|
||||
"monitors.keyword": "Keyword in response",
|
||||
"monitors.keyword_absent": "Fail if the keyword is present",
|
||||
"monitors.last_24h": "last 24 hours",
|
||||
"monitors.last_90d": "Last 90 days",
|
||||
"monitors.latency_24h": "Latency, last 24 hours",
|
||||
"monitors.latency": "Average latency",
|
||||
"monitors.method": "Method",
|
||||
"monitors.new": "New monitor",
|
||||
"monitors.range": "Time range",
|
||||
"monitors.range_note": "SLA and bars: last {{.Range}}",
|
||||
"monitors.recent": "Recent checks",
|
||||
"monitors.regions": "Regions",
|
||||
"monitors.regions_hint": "Checked from a random checker in each selected region. Your own regions are listed first.",
|
||||
"monitors.sla": "SLA",
|
||||
"monitors.sla_table": "SLA by period",
|
||||
"monitors.target": "Target",
|
||||
"monitors.target_hint": "URL for HTTP, host:port for TCP and TLS, host name for DNS and ICMP.",
|
||||
"monitors.timeout": "Timeout (ms)",
|
||||
|
||||
@@ -243,6 +243,122 @@ func (q *Queries) LatestResultsForMonitor(ctx context.Context, arg LatestResults
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const rangeBuckets = `-- name: RangeBuckets :many
|
||||
SELECT monitor_id, time_bucket($2::text::interval, time)::timestamptz AS bucket,
|
||||
count(*)::bigint AS total, count(*) FILTER (WHERE ok)::bigint AS ok_count,
|
||||
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= $3
|
||||
AND ($4::uuid IS NULL OR monitor_id = $4)
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2
|
||||
`
|
||||
|
||||
type RangeBucketsParams struct {
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since time.Time
|
||||
MonitorID *uuid.UUID
|
||||
}
|
||||
|
||||
type RangeBucketsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Bucket time.Time
|
||||
Total int64
|
||||
OkCount int64
|
||||
AvgLatencyMs float32
|
||||
}
|
||||
|
||||
// Raw results bucketed by width since a point in time, for short ranges.
|
||||
func (q *Queries) RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error) {
|
||||
rows, err := q.db.Query(ctx, rangeBuckets,
|
||||
arg.OrgID,
|
||||
arg.Width,
|
||||
arg.Since,
|
||||
arg.MonitorID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []RangeBucketsRow{}
|
||||
for rows.Next() {
|
||||
var i RangeBucketsRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Bucket,
|
||||
&i.Total,
|
||||
&i.OkCount,
|
||||
&i.AvgLatencyMs,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const rangeBucketsHourly = `-- name: RangeBucketsHourly :many
|
||||
SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucket,
|
||||
sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count,
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= $3
|
||||
AND ($4::uuid IS NULL OR monitor_id = $4)
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2
|
||||
`
|
||||
|
||||
type RangeBucketsHourlyParams struct {
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since interface{}
|
||||
MonitorID *uuid.UUID
|
||||
}
|
||||
|
||||
type RangeBucketsHourlyRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Bucket time.Time
|
||||
Total int64
|
||||
OkCount int64
|
||||
AvgLatencyMs float32
|
||||
}
|
||||
|
||||
// The hourly aggregate rebucketed by width, for ranges of days.
|
||||
func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourlyParams) ([]RangeBucketsHourlyRow, error) {
|
||||
rows, err := q.db.Query(ctx, rangeBucketsHourly,
|
||||
arg.OrgID,
|
||||
arg.Width,
|
||||
arg.Since,
|
||||
arg.MonitorID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []RangeBucketsHourlyRow{}
|
||||
for rows.Next() {
|
||||
var i RangeBucketsHourlyRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Bucket,
|
||||
&i.Total,
|
||||
&i.OkCount,
|
||||
&i.AvgLatencyMs,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const recentResults = `-- name: RecentResults :many
|
||||
SELECT time, region, ok, latency_ms, status_code, error
|
||||
FROM check_results
|
||||
|
||||
@@ -176,6 +176,38 @@ func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMoni
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const incidentsSince = `-- name: IncidentsSince :many
|
||||
SELECT monitor_id, started_at, resolved_at FROM incidents
|
||||
WHERE resolved_at IS NULL OR resolved_at > $1
|
||||
`
|
||||
|
||||
type IncidentsSinceRow struct {
|
||||
MonitorID uuid.UUID
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
}
|
||||
|
||||
// Incidents overlapping the time since $1, for SLA calculation.
|
||||
func (q *Queries) IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) {
|
||||
rows, err := q.db.Query(ctx, incidentsSince, resolvedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []IncidentsSinceRow{}
|
||||
for rows.Next() {
|
||||
var i IncidentsSinceRow
|
||||
if err := rows.Scan(&i.MonitorID, &i.StartedAt, &i.ResolvedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listChannels = `-- name: ListChannels :many
|
||||
SELECT id, org_id, name, type, config, enabled, created_at, updated_at FROM notification_channels ORDER BY name
|
||||
`
|
||||
|
||||
@@ -6,6 +6,7 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -88,6 +89,8 @@ type Querier interface {
|
||||
// Per monitor and hour since $2, across all regions.
|
||||
HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error)
|
||||
IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error)
|
||||
// Incidents overlapping the time since $1, for SLA calculation.
|
||||
IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error)
|
||||
// check_results and its aggregates have no row-level security (see
|
||||
// migration 00013). Every query here must filter by org_id.
|
||||
InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error)
|
||||
@@ -143,6 +146,10 @@ type Querier interface {
|
||||
OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error)
|
||||
OpenIncidents(ctx context.Context) ([]Incident, error)
|
||||
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
|
||||
// Raw results bucketed by width since a point in time, for short ranges.
|
||||
RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error)
|
||||
// The hourly aggregate rebucketed by width, for ranges of days.
|
||||
RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourlyParams) ([]RangeBucketsHourlyRow, error)
|
||||
RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error)
|
||||
RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error
|
||||
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
|
||||
|
||||
@@ -55,3 +55,25 @@ FROM check_results_1d
|
||||
WHERE org_id = $1 AND monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND bucket >= $2
|
||||
GROUP BY monitor_id, bucket
|
||||
ORDER BY monitor_id, bucket;
|
||||
|
||||
-- name: RangeBuckets :many
|
||||
-- Raw results bucketed by width since a point in time, for short ranges.
|
||||
SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, time)::timestamptz AS bucket,
|
||||
count(*)::bigint AS total, count(*) FILTER (WHERE ok)::bigint AS ok_count,
|
||||
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= sqlc.arg(since)
|
||||
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id))
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
|
||||
-- name: RangeBucketsHourly :many
|
||||
-- The hourly aggregate rebucketed by width, for ranges of days.
|
||||
SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timestamptz AS bucket,
|
||||
sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count,
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= sqlc.arg(since)
|
||||
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id))
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
@@ -89,3 +89,8 @@ SELECT * FROM incidents
|
||||
WHERE monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND (resolved_at IS NULL OR resolved_at > sqlc.arg(since))
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 50;
|
||||
|
||||
-- name: IncidentsSince :many
|
||||
-- Incidents overlapping the time since $1, for SLA calculation.
|
||||
SELECT monitor_id, started_at, resolved_at FROM incidents
|
||||
WHERE resolved_at IS NULL OR resolved_at > $1;
|
||||
+13
-5
@@ -98,20 +98,28 @@ type LatencyLine struct {
|
||||
Height int
|
||||
}
|
||||
|
||||
// Latency plots the average latency of buckets, oldest first.
|
||||
func Latency(buckets []Bucket, width, height int) LatencyLine {
|
||||
// Latency plots the average latency of buckets, oldest first, placing each
|
||||
// point at its time within [from, to] so the line lines up with the bars.
|
||||
// Buckets without results are skipped.
|
||||
func Latency(buckets []Bucket, from, to time.Time, width, height int) LatencyLine {
|
||||
l := LatencyLine{Width: width, Height: height}
|
||||
var max float32
|
||||
var points []Bucket
|
||||
for _, b := range buckets {
|
||||
if b.Total == 0 || b.Start.Before(from) {
|
||||
continue
|
||||
}
|
||||
points = append(points, b)
|
||||
max = maxf(max, b.Latency)
|
||||
}
|
||||
if len(buckets) < 2 || max == 0 {
|
||||
span := to.Sub(from)
|
||||
if len(points) < 2 || max == 0 || span <= 0 {
|
||||
return l
|
||||
}
|
||||
l.MaxMS = int(max)
|
||||
var sb strings.Builder
|
||||
for i, b := range buckets {
|
||||
x := float64(i) * float64(width) / float64(len(buckets)-1)
|
||||
for _, b := range points {
|
||||
x := float64(b.Start.Sub(from)) / float64(span) * float64(width)
|
||||
y := float64(height) - float64(b.Latency/max)*float64(height-2) - 1
|
||||
fmt.Fprintf(&sb, "%.1f,%.1f ", x, y)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -31,3 +32,15 @@ func TestPercent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLatencyPlacesPointsByTime(t *testing.T) {
|
||||
from := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
to := from.Add(10 * time.Minute)
|
||||
l := Latency([]Bucket{
|
||||
{Start: from.Add(5 * time.Minute), Total: 1, Latency: 100},
|
||||
{Start: from.Add(10 * time.Minute), Total: 1, Latency: 50},
|
||||
}, from, to, 100, 10)
|
||||
if !strings.HasPrefix(l.Points, "50.0,") || !strings.Contains(l.Points, " 100.0,") {
|
||||
t.Errorf("Latency().Points = %q, want points at x=50 and x=100", l.Points)
|
||||
}
|
||||
}
|
||||
+64
-17
@@ -51,6 +51,33 @@ type DashboardView struct {
|
||||
Empty bool
|
||||
CanWrite bool
|
||||
Counts map[Status]int
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
}
|
||||
|
||||
// RangeOption is an entry of the range switcher.
|
||||
type RangeOption struct {
|
||||
Key string
|
||||
Active bool
|
||||
URL string
|
||||
}
|
||||
|
||||
// SLAEntry is one window of the SLA table.
|
||||
type SLAEntry struct {
|
||||
Label string
|
||||
Value string
|
||||
}
|
||||
|
||||
templ rangeSwitch(opts []RangeOption) {
|
||||
<nav class="flex border border-rule font-mono text-xs" aria-label={ i18n.T(ctx, "monitors.range") }>
|
||||
for _, o := range opts {
|
||||
if o.Active {
|
||||
<span class="bg-ink px-2 py-1 text-paper" aria-current="true">{ o.Key }</span>
|
||||
} else {
|
||||
<a href={ templ.SafeURL(o.URL) } class="px-2 py-1 text-muted hover:text-ink">{ o.Key }</a>
|
||||
}
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
|
||||
templ statusDot(s Status) {
|
||||
@@ -96,6 +123,7 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
<div class="mb-6 flex items-baseline justify-between gap-4">
|
||||
<h1 class="text-lg font-semibold">{ i18n.T(ctx, "console.monitors.title") }</h1>
|
||||
<div class="flex items-center gap-5 font-mono text-xs text-muted">
|
||||
@rangeSwitch(v.Ranges)
|
||||
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusPaused} {
|
||||
if v.Counts[s] > 0 {
|
||||
<span class="flex items-center gap-1.5">
|
||||
@@ -118,7 +146,7 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
@groupBlock(g)
|
||||
}
|
||||
</div>
|
||||
<p class="mt-3 text-right text-xs text-muted">{ i18n.T(ctx, "monitors.last_24h") }</p>
|
||||
<p class="mt-3 text-right text-xs text-muted">{ i18n.T(ctx, "monitors.range_note", "Range", v.Range) }</p>
|
||||
}
|
||||
<p class="mt-8 text-sm"><a href="/groups" class="text-muted hover:text-ink">{ i18n.T(ctx, "groups.manage") }</a></p>
|
||||
}
|
||||
@@ -188,6 +216,9 @@ type IncidentRow struct {
|
||||
// MonitorDetailView is the data of a monitor page.
|
||||
type MonitorDetailView struct {
|
||||
Row MonitorRow
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
SLAs []SLAEntry
|
||||
Interval string
|
||||
Daily []Bar
|
||||
Uptime90 string
|
||||
@@ -212,6 +243,37 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
|
||||
<a href={ templ.SafeURL("/monitors/" + v.Row.ID + "/edit") } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "sso.action.edit") }</a>
|
||||
}
|
||||
</div>
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex items-center justify-between gap-4">
|
||||
<h2 class="text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.history", "Range", v.Range) }</h2>
|
||||
@rangeSwitch(v.Ranges)
|
||||
</div>
|
||||
<div class="mb-1 flex items-baseline justify-between font-mono text-xs text-muted">
|
||||
<span>{ i18n.T(ctx, "monitors.sla") }</span>
|
||||
<span class="text-sm text-ink">{ v.Row.Uptime }</span>
|
||||
</div>
|
||||
@bars(v.Row.Bars, 28)
|
||||
if v.Latency.Points != "" {
|
||||
<div class="mt-4 mb-1 flex justify-between font-mono text-xs text-muted">
|
||||
<span>{ i18n.T(ctx, "monitors.latency") }</span>
|
||||
<span>max { strconv.Itoa(v.Latency.MaxMS) } ms</span>
|
||||
</div>
|
||||
<svg viewBox={ "0 0 " + strconv.Itoa(v.Latency.Width) + " " + strconv.Itoa(v.Latency.Height) } preserveAspectRatio="none" class="block h-24 w-full border-b border-rule">
|
||||
<polyline points={ v.Latency.Points } fill="none" class="stroke-ink" stroke-width="1.5" vector-effect="non-scaling-stroke"></polyline>
|
||||
</svg>
|
||||
}
|
||||
</section>
|
||||
<section class="mb-10">
|
||||
@sectionHeading("monitors.sla_table")
|
||||
<dl class="grid grid-cols-3 gap-px border border-rule bg-rule sm:grid-cols-7">
|
||||
for _, e := range v.SLAs {
|
||||
<div class="bg-paper px-3 py-2">
|
||||
<dt class="font-mono text-xs text-muted">{ e.Label }</dt>
|
||||
<dd class="font-mono text-sm">{ e.Value }</dd>
|
||||
</div>
|
||||
}
|
||||
</dl>
|
||||
</section>
|
||||
<section class="mb-10">
|
||||
<div class="mb-2 flex items-baseline justify-between">
|
||||
@sectionHeading("monitors.last_90d")
|
||||
@@ -219,7 +281,7 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
|
||||
</div>
|
||||
@bars(v.Daily, 28)
|
||||
</section>
|
||||
<div class="mb-10 grid gap-10 md:grid-cols-2">
|
||||
<div class="mb-10">
|
||||
<section>
|
||||
@sectionHeading("monitors.regions")
|
||||
<ul class="divide-y divide-rule border-y border-rule text-sm">
|
||||
@@ -232,21 +294,6 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
<section>
|
||||
<div class="mb-4 flex items-baseline justify-between">
|
||||
@sectionHeading("monitors.latency_24h")
|
||||
if v.Latency.MaxMS > 0 {
|
||||
<span class="font-mono text-xs text-muted">max { strconv.Itoa(v.Latency.MaxMS) } ms</span>
|
||||
}
|
||||
</div>
|
||||
if v.Latency.Points != "" {
|
||||
<svg viewBox={ "0 0 " + strconv.Itoa(v.Latency.Width) + " " + strconv.Itoa(v.Latency.Height) } preserveAspectRatio="none" class="block h-24 w-full border-b border-rule">
|
||||
<polyline points={ v.Latency.Points } fill="none" class="stroke-ink" stroke-width="1.5" vector-effect="non-scaling-stroke"></polyline>
|
||||
</svg>
|
||||
} else {
|
||||
<p class="text-sm text-muted">–</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
if len(v.Incidents) > 0 {
|
||||
<section class="mb-10">
|
||||
|
||||
+970
-765
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// trimPercent cuts v to digits decimals instead of rounding, so 99.9996
|
||||
// never reads as a perfect 100. The epsilon absorbs float noise such as
|
||||
// 99.12 being stored as 99.1199999.
|
||||
func trimPercent(v float64, digits int) string {
|
||||
scale := math.Pow(10, float64(digits))
|
||||
v = math.Floor(v*scale+1e-6) / scale
|
||||
return strconv.FormatFloat(v, 'f', digits, 64) + "%"
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TimeRange is a selectable chart window. Bars use Bucket as resolution;
|
||||
// Hourly ranges are read from the hourly aggregate instead of raw results.
|
||||
type TimeRange struct {
|
||||
Key string
|
||||
Window time.Duration
|
||||
Bucket time.Duration
|
||||
Hourly bool
|
||||
// Layout formats bar titles.
|
||||
Layout string
|
||||
}
|
||||
|
||||
// Ranges are offered on the dashboard and monitor pages, shortest first.
|
||||
var Ranges = []TimeRange{
|
||||
{Key: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"},
|
||||
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
|
||||
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
|
||||
{Key: "24h", Window: 24 * time.Hour, Bucket: 30 * time.Minute, Layout: "01-02 15:04"},
|
||||
{Key: "7d", Window: 7 * 24 * time.Hour, Bucket: 4 * time.Hour, Hourly: true, Layout: "01-02 15:04"},
|
||||
}
|
||||
|
||||
// SLAWindows are listed on monitor pages.
|
||||
var SLAWindows = []struct {
|
||||
Key string
|
||||
Window time.Duration
|
||||
}{
|
||||
{"1h", time.Hour}, {"3h", 3 * time.Hour}, {"12h", 12 * time.Hour}, {"24h", 24 * time.Hour},
|
||||
{"7d", 7 * 24 * time.Hour}, {"30d", 30 * 24 * time.Hour}, {"90d", 90 * 24 * time.Hour},
|
||||
}
|
||||
|
||||
// DefaultRange is used when the request names none.
|
||||
const DefaultRange = "24h"
|
||||
|
||||
// RangeByKey returns the range for key, falling back to the default.
|
||||
func RangeByKey(key string) TimeRange {
|
||||
if i := slices.IndexFunc(Ranges, func(r TimeRange) bool { return r.Key == key }); i >= 0 {
|
||||
return Ranges[i]
|
||||
}
|
||||
return RangeByKey(DefaultRange)
|
||||
}
|
||||
|
||||
// Bars returns the number of bars r shows.
|
||||
func (r TimeRange) Bars() int { return int(r.Window / r.Bucket) }
|
||||
|
||||
// Span is a period during which a monitor was down; End is zero while it
|
||||
// still is.
|
||||
type Span struct {
|
||||
Start, End time.Time
|
||||
}
|
||||
|
||||
// SLA returns the fraction of [from, to] not covered by down spans, or -1
|
||||
// if the window is empty, e.g. because the monitor did not exist yet.
|
||||
// Overlapping spans count once.
|
||||
func SLA(down []Span, from, to time.Time) float64 {
|
||||
if !to.After(from) {
|
||||
return -1
|
||||
}
|
||||
clipped := make([]Span, 0, len(down))
|
||||
for _, s := range down {
|
||||
end := s.End
|
||||
if end.IsZero() || end.After(to) {
|
||||
end = to
|
||||
}
|
||||
start := s.Start
|
||||
if start.Before(from) {
|
||||
start = from
|
||||
}
|
||||
if end.After(start) {
|
||||
clipped = append(clipped, Span{start, end})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(clipped, func(a, b Span) int { return a.Start.Compare(b.Start) })
|
||||
var downtime time.Duration
|
||||
var cur Span
|
||||
for i, s := range clipped {
|
||||
switch {
|
||||
case i == 0:
|
||||
cur = s
|
||||
case !s.Start.After(cur.End):
|
||||
if s.End.After(cur.End) {
|
||||
cur.End = s.End
|
||||
}
|
||||
default:
|
||||
downtime += cur.End.Sub(cur.Start)
|
||||
cur = s
|
||||
}
|
||||
}
|
||||
if len(clipped) > 0 {
|
||||
downtime += cur.End.Sub(cur.Start)
|
||||
}
|
||||
return 1 - float64(downtime)/float64(to.Sub(from))
|
||||
}
|
||||
|
||||
// SLAText formats an SLA for display.
|
||||
func SLAText(r float64) string {
|
||||
if r < 0 {
|
||||
return "–"
|
||||
}
|
||||
return PercentPrecise(r)
|
||||
}
|
||||
|
||||
// PercentPrecise shows enough digits for SLA targets such as 99.95%.
|
||||
func PercentPrecise(r float64) string {
|
||||
switch {
|
||||
case r >= 1:
|
||||
return "100%"
|
||||
case r >= 0.999:
|
||||
return trimPercent(r*100, 3)
|
||||
case r >= 0.99:
|
||||
return trimPercent(r*100, 2)
|
||||
}
|
||||
return trimPercent(r*100, 1)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSLA(t *testing.T) {
|
||||
t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
at := func(m int) time.Time { return t0.Add(time.Duration(m) * time.Minute) }
|
||||
tests := []struct {
|
||||
name string
|
||||
down []Span
|
||||
from, to time.Time
|
||||
want float64
|
||||
}{
|
||||
{"no incidents", nil, at(0), at(60), 1},
|
||||
{"six minutes down", []Span{{at(10), at(16)}}, at(0), at(60), 0.9},
|
||||
{"clipped at window start", []Span{{at(-30), at(6)}}, at(0), at(60), 0.9},
|
||||
{"ongoing", []Span{{at(54), time.Time{}}}, at(0), at(60), 0.9},
|
||||
{"overlapping counted once", []Span{{at(10), at(20)}, {at(15), at(22)}}, at(0), at(60), 0.8},
|
||||
{"outside window", []Span{{at(70), at(80)}}, at(0), at(60), 1},
|
||||
{"empty window", nil, at(60), at(60), -1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := SLA(tt.down, tt.from, tt.to); got < tt.want-1e-9 || got > tt.want+1e-9 {
|
||||
t.Errorf("%s: SLA() = %v, want %v", tt.name, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPercentPrecise(t *testing.T) {
|
||||
for r, want := range map[float64]string{1: "100%", 0.999996: "99.999%", 0.9995: "99.950%", 0.9912: "99.12%", 0.5: "50.0%"} {
|
||||
if got := PercentPrecise(r); got != want {
|
||||
t.Errorf("PercentPrecise(%v) = %q, want %q", r, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRanges(t *testing.T) {
|
||||
for _, r := range Ranges {
|
||||
if n := r.Bars(); n < 24 || n > 72 {
|
||||
t.Errorf("range %s has %d bars, want a readable number", r.Key, n)
|
||||
}
|
||||
}
|
||||
if RangeByKey("bogus").Key != DefaultRange {
|
||||
t.Error("unknown range does not fall back to the default")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user