Files
uptimesebi/internal/api/statuspage_groups.go
T
Sebastian Unterschütz 9b26b4150e
ci / image (pull_request) Successful in 4m23s
ci / lint (pull_request) Canceled after 6m9s
ci / test (pull_request) Canceled after 6m8s
ci / build (pull_request) Canceled after 6m7s
feat(statuspage): add nested status page groups and optional component details
2026-11-22 20:07:30 +01:00

403 lines
10 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 []store.StatusPageGroup
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
}
mapped := map[uuid.UUID]store.StatusPageGroup{}
var createErr error
posByParent := map[uuid.UUID]int32{}
tree.walk(func(g store.MonitorGroup, _ int) {
if createErr != nil || !needed[g.ID] {
return
}
var parentKey uuid.UUID
var parentID *uuid.UUID
if g.ParentID != nil {
if parent, ok := mapped[*g.ParentID]; ok {
pid := parent.ID
parentID = &pid
parentKey = pid
}
}
pos := posByParent[parentKey]
posByParent[parentKey] = pos + 1
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: p.Org.ID,
ParentID: parentID,
Name: g.Name,
Position: pos,
})
if err != nil {
createErr = err
return
}
mapped[g.ID] = row
created = append(created, row)
})
if createErr != nil {
return createErr
}
for _, m := range listed {
var gid *uuid.UUID
section := ""
if m.MonitorGroupID != nil {
if g, ok := mapped[*m.MonitorGroupID]; ok {
id := g.ID
gid = &id
section = g.Name
}
}
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
}); 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
}
out := make([]pageGroupView, 0, len(created))
for _, g := range created {
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
}
c.JSON(http.StatusOK, gin.H{"groups": out})
}
// 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
}