feat(console): sort the monitor list and put monitors in an order of one's own
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 10m49s
ci / test (pull_request) Successful in 14m39s
ci / build (pull_request) Canceled after 14m22s
ci / image (pull_request) Canceled after 0s

The monitor list gets a sort switcher: the organization's own order, by
default, or by name, status (problems first), uptime (worst first) or
latency (slowest first). The choice is remembered in a cookie; paging
follows it.

"Arrange monitors" shows the whole tree with each group's monitors to
drag, or move with up and down, into the order wanted; every change is
saved at once through PUT /api/v1/org/monitors/order, which needs write
access to every monitor given and is audited. Monitors without a position
follow the positioned ones, by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-25 23:35:02 +01:00
1 parent ca852c8299
commit b0d4bcc002
16 files changed
+3389 -2653

No files matched your search

+3
View File
@@ -90,6 +90,9 @@ var endpoints = []endpoint{
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
{method: "PUT", path: "/api/v1/org/monitors/order", tag: "Monitors", summary: "Put monitors in the organization's own order", perm: "monitors.write",
description: "Positions follow the order of monitor_ids, usually the monitors of one group; the monitor list sorted by its own order shows positioned monitors first, the rest by name. Needs write access to every monitor given.",
req: monitorOrderRequest{}},
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
req: monitorRequest{}, resp: monitorView{}},
+1
View File
@@ -64,6 +64,7 @@ var auditActions = map[string]string{
"PUT /api/v1/org/policy": "org.policy_update",
"POST /api/v1/org/monitors": "monitor.create",
"PUT /api/v1/org/monitors/:id": "monitor.update",
"PUT /api/v1/org/monitors/order": "monitor.order",
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
+85 -15
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math"
"net"
"net/http"
"net/url"
@@ -79,10 +80,10 @@ 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)
if !s.dashboardPage(c, &v, data) {
return
}
v.CanWrite = writableAnywhere(p, data.tree)
v.Range = data.rng.Key
var earliest time.Time
for _, m := range data.byID {
@@ -113,14 +114,64 @@ const groupMonitorsShown = 50
// ungrouped names the pseudo-group of monitors outside any group.
const ungrouped = "none"
func monitorKey(m web.MonitorRow) cursor {
id, _ := uuid.Parse(m.ID)
return cursor{S: strings.ToLower(m.Name), ID: id}
// monitorSort is an order of the monitor list: the organization's own,
// or by name, status (problems first), uptime (worst first) or latency
// (slowest first). Monitors without a position or data come last.
type monitorSort string
var monitorSorts = []monitorSort{"custom", "name", "status", "uptime", "latency"}
const sortCookie = "monitor_sort"
// sortOf returns the order asked for, remembering it in a cookie, or the
// one remembered, or the organization's own.
func sortOf(c *gin.Context) monitorSort {
if q := monitorSort(c.Query("sort")); slices.Contains(monitorSorts, q) {
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie(sortCookie, string(q), 365*24*3600, "/", "", c.Request.TLS != nil, true)
return q
}
if v, err := c.Cookie(sortCookie); err == nil && slices.Contains(monitorSorts, monitorSort(v)) {
return monitorSort(v)
}
return "custom"
}
func sortMonitors(ms []web.MonitorRow) {
// key orders m by o as a string, so pages can continue after it.
func (o monitorSort) key(m web.MonitorRow) cursor {
id, _ := uuid.Parse(m.ID)
name := strings.ToLower(m.Name)
var k string
switch o {
case "name":
k = name
case "status":
k = fmt.Sprintf("%d|%s", statusRank[m.Status], name)
case "uptime":
if m.Ratio < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%.9f|%s", m.Ratio, name)
}
case "latency":
if m.LatencyMS < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%010d|%s", math.MaxInt32-m.LatencyMS, name)
}
default:
if m.Position < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%010d|%s", m.Position, name)
}
}
return cursor{S: k, ID: id}
}
func (o monitorSort) sort(ms []web.MonitorRow) {
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
ka, kb := monitorKey(a), monitorKey(b)
ka, kb := o.key(a), o.key(b)
if c := strings.Compare(ka.S, kb.S); c != 0 {
return c
}
@@ -135,7 +186,7 @@ var dashboardStatuses = []web.Status{web.StatusUp, web.StatusDegraded, web.Statu
// value is empty, keeping the search and range but not the page.
func dashboardURL(c *gin.Context, key, value string) string {
q := url.Values{}
for _, k := range []string{"q", "range", "status"} {
for _, k := range []string{"q", "range", "status", "arrange"} {
if v := c.Query(k); v != "" {
q.Set(k, v)
}
@@ -176,6 +227,20 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
if !ok {
return false
}
order := sortOf(c)
v.Sort = string(order)
for _, o := range monitorSorts {
v.Sorts = append(v.Sorts, web.SortOption{Key: string(o), Active: o == order, URL: dashboardURL(c, "sort", string(o))})
}
// Arranging by hand shows the whole tree in the organization's order.
arranging := order == "custom" && v.CanWrite && c.Query("q") == "" && c.Query("status") == "" && c.Query("group") == ""
v.Arrange = arranging && c.Query("arrange") == "1"
if arranging {
v.ArrangeURL = dashboardURL(c, "arrange", "1")
if v.Arrange {
v.ArrangeURL = dashboardURL(c, "arrange", "")
}
}
link := func(group string) string {
q := url.Values{"group": {group}}
if r := c.Query("range"); r != "" {
@@ -185,8 +250,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
}
var capNode func(n *web.GroupNode)
capNode = func(n *web.GroupNode) {
sortMonitors(n.Monitors)
if len(n.Monitors) > groupMonitorsShown {
order.sort(n.Monitors)
if len(n.Monitors) > groupMonitorsShown && !v.Arrange {
n.More = len(n.Monitors) - groupMonitorsShown
n.Monitors = n.Monitors[:groupMonitorsShown]
n.MoreURL = link(cmp.Or(n.ID, ungrouped))
@@ -213,8 +278,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
hits = append(hits, m)
}
}
sortMonitors(hits)
v.Results, info = pageSlice(hits, pg, monitorKey)
order.sort(hits)
v.Results, info = pageSlice(hits, pg, order.key)
case group != "":
var focus web.GroupNode
found := false
@@ -239,8 +304,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
c.Redirect(http.StatusSeeOther, "/")
return false
}
sortMonitors(focus.Monitors)
focus.Monitors, info = pageSlice(focus.Monitors, pg, monitorKey)
order.sort(focus.Monitors)
focus.Monitors, info = pageSlice(focus.Monitors, pg, order.key)
for i := range focus.Children {
capNode(&focus.Children[i])
}
@@ -448,7 +513,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
continue
}
d.byID[m.ID] = m
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"}
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–", Position: -1, LatencyMS: -1}
if m.Position != nil {
row.Position = int(*m.Position)
}
keys := idStrings(regionsOf[m.ID])
if check.Passive(check.Type(m.Type)) {
// The target of a heartbeat is its secret ping token.
@@ -509,8 +577,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
sum += l
}
row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies)))
row.LatencyMS = int(sum / int32(len(latencies)))
}
row.Uptime = web.SLAText(d.slaFor(m, rng.Window))
row.Ratio = d.slaFor(m, rng.Window)
row.Uptime = web.SLAText(row.Ratio)
row.Bars = web.UptimeBars(d.buckets[m.ID], now, rng.Bucket, rng.Bars(), rng.Layout)
d.rows = append(d.rows, row)
}
+66
View File
@@ -83,3 +83,69 @@ func TestPageEditorOffersAddAndRemoveAll(t *testing.T) {
}
}
}
func TestMonitorOrder(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("ord")+".test", uniq("ord-"))
ids := map[string]string{}
for _, n := range []string{"Alpha", "Bravo", "Charlie"} {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": n, "type": "http", "target": "https://" + strings.ToLower(n) + ".test", "interval_seconds": 60, "regions": []string{region}})
ids[n] = m["id"].(string)
}
order := func(html string, names ...string) bool {
last := -1
for _, n := range names {
i := strings.Index(html, ">"+n+"<")
if i < last || i < 0 {
return false
}
last = i
}
return true
}
// Without an order of its own, by name.
if _, _, html := owner.page("/"); !order(html, "Alpha", "Bravo", "Charlie") {
t.Error("monitors without positions are not by name")
}
st, body := owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Charlie"], ids["Alpha"]}})
if st != http.StatusNoContent {
t.Fatalf("order = %d %v", st, body)
}
// Positioned ones first, in their order; the rest after, by name.
_, _, html := owner.page("/")
if !order(html, "Charlie", "Alpha", "Bravo") {
t.Error("the list does not follow the organization's order")
}
if !strings.Contains(html, "?arrange=1") || !strings.Contains(html, "?sort=name") {
t.Error("the dashboard offers neither arranging nor sorting")
}
if _, _, arr := owner.page("/?arrange=1"); !strings.Contains(arr, `data-sortable="/org/monitors/order"`) || !strings.Contains(arr, `data-sort-id="`+ids["Charlie"]+`"`) {
t.Error("arranging does not show the sortable list")
}
// Sorting by name is remembered until changed.
if _, _, byName := owner.page("/?sort=name"); !order(byName, "Alpha", "Bravo", "Charlie") {
t.Error("?sort=name does not sort by name")
}
if _, _, again := owner.page("/"); !order(again, "Alpha", "Bravo", "Charlie") || strings.Contains(again, "?arrange=1") {
t.Error("the sort order is not remembered, or arranging is offered outside the own order")
}
owner.page("/?sort=custom")
// Unknown and duplicate monitors are refused, and nothing changes.
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], "00000000-0000-0000-0000-000000000001"}})
expect(t, "unknown monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], ids["Bravo"]}})
expect(t, "duplicate monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
if _, _, html := owner.page("/"); !order(html, "Charlie", "Alpha", "Bravo") {
t.Error("a refused order changed the list")
}
// Another organization cannot touch them.
other := e.browser(t)
other.signup("x@"+uniq("ord")+".test", uniq("ord-"))
st, body = other.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Alpha"]}})
expect(t, "another organization's monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
}
+66
View File
@@ -0,0 +1,66 @@
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
type monitorOrderRequest struct {
// MonitorIDs in the order wanted; usually the monitors of one group.
MonitorIDs []uuid.UUID `json:"monitor_ids" binding:"required,min=1,max=1000"`
}
// orderMonitors stores the organization's own order of the monitors given,
// which the monitor list follows when sorted by its own order. It needs
// write access to every one of them.
func (s *Server) orderMonitors(c *gin.Context) {
var req monitorOrderRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
errDenied := errors.New("denied")
seen := map[uuid.UUID]bool{}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
for i, id := range req.MonitorIDs {
if seen[id] {
return pgx.ErrNoRows
}
seen[id] = true
m, err := q.GetMonitor(ctx, id)
if err != nil {
return err
}
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
return errDenied
}
if _, err := q.SetMonitorPosition(ctx, store.SetMonitorPositionParams{ID: id, Position: new(int32(i))}); err != nil {
return err
}
}
return nil
})
switch {
case errors.Is(err, errDenied):
fail(c, http.StatusForbidden, "forbidden")
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
case err != nil:
internalError(c, err)
default:
c.Status(http.StatusNoContent)
}
}
+1
View File
@@ -156,6 +156,7 @@ func (s *Server) Mount(r gin.IRouter) {
// scoped to a group grant access below that group only.
org.GET("/monitors", s.listMonitors)
org.POST("/monitors", s.createMonitor)
org.PUT("/monitors/order", s.orderMonitors)
org.PUT("/monitors/:id", s.updateMonitor)
org.DELETE("/monitors/:id", s.deleteMonitor)
org.GET("/monitors/:id/evidence", s.listEvidence)