Files
uptimesebi/internal/api/statuspage_groups.go
T
Sebastian UnterschützandClaude Opus 5.5 52d2ce25c9
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 10m59s
ci / test (pull_request) Successful in 12m44s
ci / build (pull_request) Successful in 18m14s
ci / image (pull_request) Canceled after 1m1s
perf(statuspages): page the monitor list and batch the group import
With thousands of monitors on a status page the editor was tens of
megabytes, as every row carried the options of all groups, and
importing the monitor groups updated each monitor in its own statement.

- The monitors of the editor are shown 50 at a time. All rows stay in
  the form, as saving replaces the page's monitors.
- Rows carry their own group only and get the other options from the
  row template once shown or focused.
- The filter matches a monitor's name and group path only, no longer
  the names of the groups in its select.
- The import creates the groups one nesting level at a time and files
  all monitors in one statement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 23:38:08 +01:00

414 lines
11 KiB
Go

package api
import (
"context"
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// pageGroupTree organizes one status page's nested groups in display order.
type pageGroupTree struct {
byID map[uuid.UUID]store.StatusPageGroup
children map[uuid.UUID][]uuid.UUID
roots []uuid.UUID
}
func newPageGroupTree(groups []store.StatusPageGroup) pageGroupTree {
t := pageGroupTree{
byID: make(map[uuid.UUID]store.StatusPageGroup, len(groups)),
children: map[uuid.UUID][]uuid.UUID{},
}
for _, g := range groups {
t.byID[g.ID] = g
}
for _, g := range groups {
if g.ParentID != nil {
if _, ok := t.byID[*g.ParentID]; ok {
t.children[*g.ParentID] = append(t.children[*g.ParentID], g.ID)
continue
}
}
t.roots = append(t.roots, g.ID)
}
return t
}
func (t pageGroupTree) walk(fn func(g store.StatusPageGroup, depth int)) {
var visit func(ids []uuid.UUID, depth int)
visit = func(ids []uuid.UUID, depth int) {
for _, id := range ids {
fn(t.byID[id], depth)
visit(t.children[id], depth+1)
}
}
visit(t.roots, 0)
}
type pageGroupView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
ParentID *uuid.UUID `json:"parent_id"`
Position int32 `json:"position"`
}
type pageGroupRequest struct {
Name string `json:"name" binding:"required,max=100"`
ParentID *uuid.UUID `json:"parent_id"`
Position int32 `json:"position"`
}
func pageGroupError(c *gin.Context, err error) bool {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return false
}
switch {
case pgErr.ConstraintName == "status_page_groups_cycle", pgErr.ConstraintName == "status_page_groups_check":
fail(c, http.StatusUnprocessableEntity, "group_cycle")
case pgErr.ConstraintName == "status_page_groups_depth":
fail(c, http.StatusUnprocessableEntity, "group_too_deep")
case pgErr.Code == "23503":
fail(c, http.StatusUnprocessableEntity, "invalid_group")
default:
return false
}
return true
}
func (s *Server) listStatusPageGroups(c *gin.Context) {
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var groups []store.StatusPageGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
var err error
groups, err = q.ListStatusPageGroups(ctx, pageID)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
out := make([]pageGroupView, 0, len(groups))
newPageGroupTree(groups).walk(func(g store.StatusPageGroup, _ int) {
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
})
c.JSON(http.StatusOK, gin.H{"groups": out})
}
func (s *Server) createStatusPageGroup(c *gin.Context) {
var req pageGroupRequest
if !bind(c, &req) {
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var g store.StatusPageGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
var err error
g, err = q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: p.Org.ID,
ParentID: req.ParentID,
Name: req.Name,
Position: req.Position,
})
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if pageGroupError(c, err) {
return
}
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
func (s *Server) updateStatusPageGroup(c *gin.Context) {
groupID, err := uuid.Parse(c.Param("group_id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req pageGroupRequest
if !bind(c, &req) {
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var g store.StatusPageGroup
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
g, err = q.UpdateStatusPageGroup(ctx, store.UpdateStatusPageGroupParams{
ID: groupID,
PageID: pageID,
Name: req.Name,
ParentID: req.ParentID,
Position: req.Position,
})
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if pageGroupError(c, err) {
return
}
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
// deleteStatusPageGroup moves child groups and monitors up to the deleted
// group's parent before removing the group.
func (s *Server) deleteStatusPageGroup(c *gin.Context) {
groupID, err := uuid.Parse(c.Param("group_id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
groups, err := q.ListStatusPageGroups(ctx, pageID)
if err != nil {
return err
}
target, ok := newPageGroupTree(groups).byID[groupID]
if !ok {
return pgx.ErrNoRows
}
if err := q.ReparentStatusPageGroupChildren(ctx, store.ReparentStatusPageGroupChildrenParams{
PageID: pageID, ParentID: &groupID, ParentID_2: target.ParentID,
}); err != nil {
return err
}
if err := q.ReparentStatusPageGroupMonitors(ctx, store.ReparentStatusPageGroupMonitorsParams{
PageID: pageID, GroupID: &groupID, GroupID_2: target.ParentID,
}); err != nil {
return err
}
n, err := q.DeleteStatusPageGroup(ctx, store.DeleteStatusPageGroupParams{ID: groupID, PageID: pageID})
if err != nil {
return err
}
if n == 0 {
return pgx.ErrNoRows
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// importStatusPageGroups copies the organization's monitor group hierarchy
// onto the status page and maps the page's monitors into those groups. When
// the page already lists monitors, only groups containing those monitors (and
// their ancestors) are imported; otherwise the full monitor group tree is
// copied as a starting layout.
func (s *Server) importStatusPageGroups(c *gin.Context) {
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var created []pageGroupView
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
}
orgGroups, err := q.ListGroups(ctx)
if err != nil {
return err
}
listed, err := q.StatusPageMonitors(ctx, pageID)
if err != nil {
return err
}
tree := newGroupTree(orgGroups)
needed := map[uuid.UUID]bool{}
if len(listed) == 0 {
for id := range tree.byID {
needed[id] = true
}
} else {
for _, m := range listed {
for cur := m.MonitorGroupID; cur != nil; {
g, ok := tree.byID[*cur]
if !ok || needed[g.ID] {
break
}
needed[g.ID] = true
cur = g.ParentID
}
}
}
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
return err
}
// Large organizations have thousands of monitors and hundreds of
// groups, so both are written in a few statements: the groups one
// level of nesting at a time, as parents must exist before their
// children, the monitors all at once.
mapped := map[uuid.UUID]pageGroupView{}
var levels []store.CreateStatusPageGroupsParams
posByParent := map[uuid.UUID]int32{}
tree.walk(func(g store.MonitorGroup, depth int) {
if !needed[g.ID] {
return
}
var parentID *uuid.UUID
if g.ParentID != nil {
if parent, ok := mapped[*g.ParentID]; ok {
pid := parent.ID
parentID = &pid
}
}
var parentKey uuid.UUID
if parentID != nil {
parentKey = *parentID
}
pos := posByParent[parentKey]
posByParent[parentKey] = pos + 1
row := pageGroupView{ID: uuid.New(), Name: g.Name, ParentID: parentID, Position: pos}
mapped[g.ID] = row
created = append(created, row)
for len(levels) <= depth {
levels = append(levels, store.CreateStatusPageGroupsParams{PageID: pageID, OrgID: p.Org.ID})
}
l := &levels[depth]
l.Ids = append(l.Ids, row.ID)
l.ParentIds = append(l.ParentIds, parentKey)
l.Names = append(l.Names, row.Name)
l.Positions = append(l.Positions, row.Position)
})
for _, l := range levels {
if len(l.Ids) == 0 {
continue
}
if err := q.CreateStatusPageGroups(ctx, l); err != nil {
return err
}
}
set := store.SetStatusPageMonitorGroupsParams{PageID: pageID}
for _, m := range listed {
var gid uuid.UUID
section := ""
if m.MonitorGroupID != nil {
if g, ok := mapped[*m.MonitorGroupID]; ok {
gid = g.ID
section = g.Name
}
}
set.MonitorIds = append(set.MonitorIds, m.MonitorID)
set.GroupIds = append(set.GroupIds, gid)
set.Sections = append(set.Sections, section)
}
if len(set.MonitorIds) > 0 {
if err := q.SetStatusPageMonitorGroups(ctx, set); err != nil {
return err
}
}
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
if created == nil {
created = []pageGroupView{}
}
c.JSON(http.StatusOK, gin.H{"groups": created})
}
// resolvePageMonitorGroup returns the status page group ID and section label
// for a component entry, creating a top-level group when a legacy caller passes
// only section.
func resolvePageMonitorGroup(
ctx context.Context,
q *store.Queries,
pageID, orgID uuid.UUID,
m pageMonitor,
groupsByID map[uuid.UUID]store.StatusPageGroup,
topByName map[string]store.StatusPageGroup,
nextPos *int32,
) (*uuid.UUID, string, error) {
if m.GroupID != nil {
if g, ok := groupsByID[*m.GroupID]; ok {
return m.GroupID, g.Name, nil
}
// Let the database foreign key reject unknown or foreign group IDs.
return m.GroupID, strings.TrimSpace(m.Section), nil
}
sec := strings.TrimSpace(m.Section)
if sec == "" {
return nil, "", nil
}
if g, ok := topByName[sec]; ok {
id := g.ID
return &id, g.Name, nil
}
g, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: orgID,
Name: sec,
Position: *nextPos,
})
if err != nil {
return nil, "", err
}
*nextPos++
groupsByID[g.ID] = g
topByName[sec] = g
id := g.ID
return &id, g.Name, nil
}