Files
uptimesebi/internal/api/console.go
Sebastian UnterschützandClaude Opus 5.5 b3f19e20ad feat(web): show monitors as a group tree and limit roles to groups
The dashboard nests groups with an aggregated status, the monitor editor
offers the groups one may write to, a page manages groups, and members
can be assigned roles limited to a group or a status page. Settings move
to their own page to keep the navigation short.

Closes #57

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 09:19:55 +01:00

636 lines
20 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"time"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
const timeLayout = "2006-01-02 15:04 MST"
func (s *Server) registerConsole(r gin.IRouter) {
r.GET("/", s.dashboard)
// Monitor pages check permissions per group themselves.
r.GET("/monitors/new", s.orgPage("monitors.new", "", s.monitorEditor))
r.GET("/monitors/:id", s.orgPage("console.monitors.title", "", s.monitorDetail))
r.GET("/monitors/:id/edit", s.orgPage("monitors.edit", "", s.monitorEditor))
r.GET("/groups", s.orgPage("groups.title", "", s.groupsView))
r.GET("/settings", s.settingsIndex)
r.GET("/incidents", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentsView))
r.GET("/settings/channels", s.orgPage("channels.title", authz.NotificationsRead, s.channelsView))
r.GET("/statuspages", s.orgPage("pages.title", "", s.statusPagesView))
r.GET("/statuspages/:id", s.orgPage("pages.title", "", s.statusPageEditor))
}
// dashboard is the landing page. Unlike other console pages it renders for
// users without an organization or permission instead of redirecting, since
// it is where those redirects lead.
func (s *Server) dashboard(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
me, p, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return
}
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
if p != nil && me.Policy == "" {
data, err := s.loadMonitorData(c.Request.Context(), p)
if err != nil {
internalError(c, err)
return
}
v.Root = buildGroupNodes(data.tree, data.rows)
v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0
v.CanWrite = writableAnywhere(p, data.tree)
for _, m := range data.rows {
v.Counts[m.Status]++
}
}
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
}
type monitorData struct {
tree groupTree
rows []web.MonitorRow
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.
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{}}
now := time.Now()
var (
monitors []store.Monitor
assigned []store.AllMonitorRegionsRow
regions []store.Region
latest []store.LatestResultsRow
open []store.Incident
hourly []store.HourlyBucketsRow
)
var groups []store.MonitorGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if groups, err = q.ListGroups(ctx); err != nil {
return err
}
if monitors, err = q.ListMonitors(ctx); err != nil {
return err
}
if assigned, err = q.AllMonitorRegions(ctx); err != nil {
return err
}
if regions, err = q.ListVisibleRegions(ctx); err != nil {
return err
}
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
return err
}
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)})
return err
})
if err != nil {
return d, err
}
d.tree = newGroupTree(groups)
for _, r := range regions {
d.regionOf[r.ID] = r
}
regionsOf := map[uuid.UUID][]uuid.UUID{}
for _, a := range assigned {
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
}
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
for _, l := range latest {
if latestOf[l.MonitorID] == nil {
latestOf[l.MonitorID] = map[string]store.LatestResultsRow{}
}
latestOf[l.MonitorID][l.Region] = l
}
down := map[uuid.UUID]bool{}
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
}
d.byID[m.ID] = m
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"}
if m.GroupID != nil {
row.GroupID = m.GroupID.String()
}
var latencies []int32
failing, reported := 0, 0
for _, rid := range regionsOf[m.ID] {
rs := web.RegionStatus{Name: d.regionName(rid), Status: web.StatusUnknown, Detail: "–"}
if l, ok := latestOf[m.ID][rid.String()]; ok {
reported++
rs.Detail = l.Time.Format("15:04:05")
if l.Ok {
rs.Status = web.StatusUp
if l.LatencyMs != nil {
latencies = append(latencies, *l.LatencyMs)
rs.Detail = fmt.Sprintf("%d ms", *l.LatencyMs)
}
} else {
failing++
rs.Status = web.StatusDown
rs.Detail = deref(l.Error)
}
}
row.Regions = append(row.Regions, rs)
}
switch {
case !m.Enabled:
row.Status = web.StatusPaused
case down[m.ID]:
row.Status = web.StatusDown
case reported == 0:
row.Status = web.StatusUnknown
case failing > 0:
row.Status = web.StatusDegraded
default:
row.Status = web.StatusUp
}
if len(latencies) > 0 {
var sum int32
for _, l := range latencies {
sum += l
}
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")
d.rows = append(d.rows, row)
}
// Problems first, then by name.
rank := map[web.Status]int{web.StatusDown: 0, web.StatusDegraded: 1, web.StatusUnknown: 2, web.StatusUp: 3, web.StatusPaused: 4}
slices.SortStableFunc(d.rows, func(a, b web.MonitorRow) int { return rank[a.Status] - rank[b.Status] })
return d, nil
}
func (d monitorData) regionName(id uuid.UUID) string {
if r, ok := d.regionOf[id]; ok {
return r.Name
}
return id.String()[:8]
}
func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
return notFoundPage(c)
}
ctx := c.Request.Context()
d, err := s.loadMonitorData(ctx, p)
if err != nil {
return nil, err
}
// byID only holds monitors the principal may read.
m, ok := d.byID[id]
if !ok {
return notFoundPage(c)
}
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),
Uptime90: "–",
}
for _, r := range d.rows {
if r.ID == id.String() {
v.Row = r
}
}
var (
daily []store.DailyBucketsRow
recent []store.RecentResultsRow
incidents []store.Incident
)
now := time.Now()
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if daily, err = q.DailyBuckets(ctx, store.DailyBucketsParams{OrgID: p.Org.ID, MonitorID: id, Bucket: now.AddDate(0, 0, -90)}); err != nil {
return err
}
if recent, err = q.RecentResults(ctx, store.RecentResultsParams{OrgID: p.Org.ID, MonitorID: id, Time: now.Add(-24 * time.Hour)}); err != nil {
return err
}
incidents, err = q.MonitorIncidents(ctx, id)
return err
})
if err != nil {
return nil, err
}
buckets := make([]web.Bucket, len(daily))
for i, b := range daily {
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")
if u := web.Uptime(buckets); u >= 0 {
v.Uptime90 = web.Percent(u)
}
for _, r := range recent[:min(len(recent), 50)] {
row := web.ResultRow{Time: r.Time.Format("01-02 15:04:05"), Region: d.regionNameString(r.Region), OK: r.Ok, Latency: "–", Detail: deref(r.Error)}
if r.LatencyMs != nil {
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMs)
}
if r.StatusCode != nil && row.Detail == "" {
row.Detail = fmt.Sprint(*r.StatusCode)
}
v.Recent = append(v.Recent, row)
}
for _, i := range incidents {
v.Incidents = append(v.Incidents, d.incidentRow(i, m.Name))
}
page.TitleID = "console.monitors.title"
return web.MonitorDetail(page, me, v), nil
}
func (d monitorData) regionNameString(id string) string {
if u, err := uuid.Parse(id); err == nil {
return d.regionName(u)
}
return id
}
func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentRow {
row := web.IncidentRow{
ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor,
Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil,
}
end := time.Now()
if i.ResolvedAt != nil {
end = *i.ResolvedAt
}
row.Duration = humanDuration(end.Sub(i.StartedAt))
var cause map[string]string
_ = json.Unmarshal(i.Cause, &cause)
for region, msg := range cause {
row.Cause = append(row.Cause, d.regionNameString(region)+": "+msg)
}
slices.Sort(row.Cause)
return row
}
// humanDuration prints the two most significant units, e.g. "2h 5m".
func humanDuration(d time.Duration) string {
d = d.Round(time.Second)
days := int(d / (24 * time.Hour))
h := int(d/time.Hour) % 24
m := int(d/time.Minute) % 60
sec := int(d/time.Second) % 60
switch {
case days > 0:
return fmt.Sprintf("%dd %dh", days, h)
case h > 0:
return fmt.Sprintf("%dh %dm", h, m)
case m > 0:
return fmt.Sprintf("%dm %ds", m, sec)
}
return fmt.Sprintf("%ds", sec)
}
func notFoundPage(c *gin.Context) (templ.Component, error) {
c.Redirect(http.StatusSeeOther, "/")
return nil, errAborted
}
// errAborted tells orgPage that the view already wrote a response.
var errAborted = errors.New("api: response already written")
func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
f := web.MonitorForm{
Type: "http", IntervalSeconds: 60, TimeoutMS: 10000, Confirmations: 2, Enabled: true,
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx",
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
}
var (
regions []store.Region
assigned []uuid.UUID
)
idParam := c.Param("id")
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if regions, err = q.ListVisibleRegions(ctx); err != nil {
return err
}
if idParam == "" {
return nil
}
id, err := uuid.Parse(idParam)
if err != nil {
return pgx.ErrNoRows
}
m, err := q.GetMonitor(ctx, id)
if err != nil {
return err
}
fillForm(&f, m)
assigned, err = q.MonitorRegions(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
return notFoundPage(c)
}
if err != nil {
return nil, err
}
for i, r := range regions {
live, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
return nil, err
}
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live})
}
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
return nil, err
}
f.Groups = writableGroups(p, t)
f.TopLevel = p.Grants.Can(authz.MonitorsWrite)
var current *uuid.UUID
if f.GroupID != "" {
id := uuid.MustParse(f.GroupID)
current = &id
}
if (idParam == "" && !writableAnywhere(p, t)) || (idParam != "" && !canInGroup(p, authz.MonitorsWrite, t, current)) {
return notFoundPage(c)
}
return web.MonitorEditor(page, me, f), nil
}
func fillForm(f *web.MonitorForm, m store.Monitor) {
f.ID, f.Name, f.Type, f.Target = m.ID.String(), m.Name, m.Type, m.Target
f.IntervalSeconds, f.TimeoutMS = int(m.IntervalSeconds), int(m.TimeoutMs)
f.Confirmations, f.Enabled = int(m.Confirmations), m.Enabled
if m.GroupID != nil {
f.GroupID = m.GroupID.String()
}
switch check.Type(m.Type) {
case check.HTTP:
var c check.HTTPConfig
_ = json.Unmarshal(m.Config, &c)
f.Method, f.ExpectStatus, f.Keyword, f.KeywordAbsent = c.Method, strings.Join(c.ExpectStatus, ", "), c.Keyword, c.KeywordAbsent
f.FollowRedirects, f.VerifyTLS = c.FollowRedirects, c.VerifyTLS
case check.DNS:
var c check.DNSConfig
_ = json.Unmarshal(m.Config, &c)
f.DNSRecord, f.DNSResolver, f.DNSExpect = c.Record, c.Resolver, c.Expect
case check.TLS:
var c check.TLSConfig
_ = json.Unmarshal(m.Config, &c)
f.TLSMinDays, f.TLSServerName = c.MinDaysValid, c.ServerName
}
}
func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.ListIncidentsRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidents(ctx)
return err
})
if err != nil {
return nil, err
}
d, err := s.loadMonitorData(ctx, p)
if err != nil {
return nil, err
}
out := make([]web.IncidentRow, len(rows))
for i, r := range rows {
out[i] = d.incidentRow(store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause,
}, r.MonitorName)
}
return web.IncidentsPage(page, me, out), nil
}
func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.NotificationChannel
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListChannels(ctx)
return err
})
if err != nil {
return nil, err
}
v := web.ChannelsView{EmailAvailable: s.smtp != nil, CanWrite: p.Grants.Can(authz.NotificationsWrite), Languages: s.catalog.Supported()}
for _, r := range rows {
cv := viewChannel(r)
target := cv.URL
if cv.Type == "email" {
target = strings.Join(cv.To, ", ")
}
v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled})
}
return web.ChannelsPage(page, me, v), nil
}
func (s *Server) pageURL(p store.StatusPage) string {
if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
return "https://" + *p.CustomDomain + "/"
}
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
}
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.StatusPage
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListStatusPages(ctx)
return err
})
if err != nil {
return nil, err
}
v := web.PagesView{CanWrite: p.Grants.Can(authz.StatusPagesWrite)}
for _, r := range rows {
if !p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
continue
}
v.Pages = append(v.Pages, web.PageRow{
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
URL: s.pageURL(r), Domain: deref(r.CustomDomain),
})
}
return web.StatusPagesPage(page, me, v), nil
}
func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
id, err := uuid.Parse(c.Param("id"))
if err != nil || !p.Grants.Can(authz.StatusPagesWrite, pageResource(id)) {
return notFoundPage(c)
}
ctx := c.Request.Context()
var (
row store.StatusPage
listed []store.StatusPageMonitorsRow
monitors []store.Monitor
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if row, err = q.GetStatusPage(ctx, id); err != nil {
return err
}
if listed, err = q.StatusPageMonitors(ctx, id); err != nil {
return err
}
monitors, err = q.ListMonitors(ctx)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
return notFoundPage(c)
}
if err != nil {
return nil, err
}
v := viewStatusPage(row)
e := web.PageEditor{
ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
Published: row.Published, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
}
if v.DomainRecord != nil {
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
}
// Listed monitors keep their order; the rest follow alphabetically.
seen := map[uuid.UUID]bool{}
for _, l := range listed {
seen[l.MonitorID] = true
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: l.MonitorID.String(), Name: l.MonitorName, Included: true, Section: l.Section, Label: l.Label})
}
for _, m := range monitors {
if !seen[m.ID] {
e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: m.ID.String(), Name: m.Name})
}
}
return web.StatusPageEditor(page, me, e), nil
}
// rank orders statuses from worst to best for aggregation.
var statusRank = map[web.Status]int{web.StatusDown: 0, web.StatusDegraded: 1, web.StatusUnknown: 2, web.StatusUp: 3, web.StatusPaused: 4}
// buildGroupNodes arranges monitor rows into the group tree. Groups show the
// worst status below them; empty groups are kept so the structure is
// visible.
func buildGroupNodes(t groupTree, rows []web.MonitorRow) web.GroupNode {
byGroup := map[string][]web.MonitorRow{}
for _, r := range rows {
byGroup[r.GroupID] = append(byGroup[r.GroupID], r)
}
var build func(id uuid.UUID) web.GroupNode
build = func(id uuid.UUID) web.GroupNode {
g := t.byID[id]
n := web.GroupNode{ID: id.String(), Name: g.Name, Status: web.StatusUnknown, Monitors: byGroup[id.String()]}
worst := 99
for _, m := range n.Monitors {
worst = min(worst, statusRank[m.Status])
}
n.Total = len(n.Monitors)
for _, child := range t.children[id] {
cn := build(child)
n.Children = append(n.Children, cn)
n.Total += cn.Total
if cn.Total > 0 {
worst = min(worst, statusRank[cn.Status])
}
}
for s, r := range statusRank {
if r == worst {
n.Status = s
}
}
return n
}
root := web.GroupNode{Monitors: byGroup[""]}
for _, id := range t.roots {
root.Children = append(root.Children, build(id))
}
return root
}
// writableGroups lists the groups p may put monitors in, indented by depth.
func writableGroups(p *principal, t groupTree) []web.GroupOption {
var out []web.GroupOption
t.walk(func(g store.MonitorGroup, depth int) {
if canInGroup(p, authz.MonitorsWrite, t, &g.ID) {
out = append(out, web.GroupOption{ID: g.ID.String(), Label: strings.Repeat("— ", depth) + g.Name})
}
})
return out
}
// writableAnywhere reports whether p may create monitors somewhere.
func writableAnywhere(p *principal, t groupTree) bool {
return p.Grants.Can(authz.MonitorsWrite) || len(writableGroups(p, t)) > 0
}
func (s *Server) groupsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
t, err := s.loadGroupTree(c.Request.Context(), p.scope())
if err != nil {
return nil, err
}
v := web.GroupsView{Parents: writableGroups(p, t), TopLevel: p.Grants.Can(authz.MonitorsWrite)}
v.CanWrite = v.TopLevel || len(v.Parents) > 0
t.walk(func(g store.MonitorGroup, depth int) {
row := web.GroupRow{ID: g.ID.String(), Name: g.Name, Depth: depth, CanWrite: canInGroup(p, authz.MonitorsWrite, t, &g.ID)}
if g.ParentID != nil {
row.ParentID = g.ParentID.String()
}
v.Groups = append(v.Groups, row)
})
return web.GroupsPage(page, me, v), nil
}
func (s *Server) settingsIndex(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login?next=/settings")
return
}
me, _, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.SettingsIndex(s.pageFor(c, "console.nav.settings"), me))
}