feat(statuspage): add nested status page groups and optional component details
This commit is contained in:
1 parent
1c31003baf
commit
9b26b4150e
26 files changed
+4566
-760
No files matched your search
+11
-1
@@ -114,8 +114,18 @@ var endpoints = []endpoint{
|
||||
req: statusPageRequest{}, resp: statusPageView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id", tag: "Status pages", summary: "Delete a status page", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "List status page groups", perm: "statuspages.read",
|
||||
resp: obj{"groups": []pageGroupView{}}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/groups", tag: "Status pages", summary: "Create a status page group", perm: "statuspages.write",
|
||||
req: pageGroupRequest{}, status: http.StatusCreated, resp: pageGroupView{}},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Rename, move or reorder a status page group", perm: "statuspages.write",
|
||||
req: pageGroupRequest{}, resp: pageGroupView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id/groups/:group_id", tag: "Status pages", summary: "Delete a status page group", perm: "statuspages.write",
|
||||
description: "Child groups and monitors move up to the deleted group's parent.", status: http.StatusNoContent},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/groups/import", tag: "Status pages", summary: "Import monitor groups into a status page", perm: "statuspages.write",
|
||||
description: "Copies the organization's monitor group tree for the page's monitors and maps them into the imported groups.", resp: obj{"groups": []pageGroupView{}}},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/monitors", tag: "Status pages", summary: "Set the monitors shown", perm: "statuspages.write",
|
||||
req: pageMonitorsRequest{}, status: http.StatusNoContent},
|
||||
description: "Assigns monitors to optional nested groups via `group_id`. Legacy `section` names are mapped to top-level groups.", req: pageMonitorsRequest{}, status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/org/statuspages/:id/domain", tag: "Status pages", summary: "Set a custom domain", perm: "statuspages.write",
|
||||
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
|
||||
|
||||
+43
-39
@@ -45,45 +45,49 @@ var auditActions = map[string]string{
|
||||
"POST /api/v1/invitations/:token/accept": "member.join",
|
||||
"POST /api/v1/invitations/:token/signup": "member.join",
|
||||
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"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",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"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",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
|
||||
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
|
||||
+52
-6
@@ -832,9 +832,11 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
row store.StatusPage
|
||||
listed []store.StatusPageMonitorsRow
|
||||
monitors []store.Monitor
|
||||
row store.StatusPage
|
||||
listed []store.StatusPageMonitorsRow
|
||||
pageGroups []store.StatusPageGroup
|
||||
orgGroups []store.MonitorGroup
|
||||
monitors []store.Monitor
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
@@ -844,6 +846,12 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if listed, err = q.StatusPageMonitors(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if pageGroups, err = q.ListStatusPageGroups(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if orgGroups, err = q.ListGroups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
monitors, err = q.ListMonitors(ctx)
|
||||
return err
|
||||
})
|
||||
@@ -856,21 +864,59 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
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,
|
||||
Published: row.Published, ShowDetails: row.ShowComponentDetails,
|
||||
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
|
||||
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
|
||||
HasOrgGroups: len(orgGroups) > 0,
|
||||
}
|
||||
if v.DomainRecord != nil {
|
||||
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
|
||||
}
|
||||
newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) {
|
||||
var parentID string
|
||||
if g.ParentID != nil {
|
||||
parentID = g.ParentID.String()
|
||||
}
|
||||
e.Groups = append(e.Groups, web.PageGroupRow{
|
||||
ID: g.ID.String(), Name: g.Name, ParentID: parentID, Position: int(g.Position), Depth: depth,
|
||||
Label: strings.Repeat("— ", depth) + g.Name,
|
||||
})
|
||||
})
|
||||
orgTree := newGroupTree(orgGroups)
|
||||
groupPath := func(gid *uuid.UUID) string {
|
||||
if gid == nil {
|
||||
return ""
|
||||
}
|
||||
var parts []string
|
||||
for cur := gid; cur != nil && len(parts) < 10; {
|
||||
g, ok := orgTree.byID[*cur]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
parts = append(parts, g.Name)
|
||||
cur = g.ParentID
|
||||
}
|
||||
slices.Reverse(parts)
|
||||
return strings.Join(parts, " / ")
|
||||
}
|
||||
// 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})
|
||||
var groupID string
|
||||
if l.GroupID != nil {
|
||||
groupID = l.GroupID.String()
|
||||
}
|
||||
e.Monitors = append(e.Monitors, web.PageMonitorOption{
|
||||
ID: l.MonitorID.String(), Name: l.MonitorName, MonitorGroupPath: groupPath(l.MonitorGroupID),
|
||||
Included: true, GroupID: groupID, 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})
|
||||
e.Monitors = append(e.Monitors, web.PageMonitorOption{
|
||||
ID: m.ID.String(), Name: m.Name, MonitorGroupPath: groupPath(m.GroupID),
|
||||
})
|
||||
}
|
||||
}
|
||||
return web.StatusPageEditor(page, me, e), nil
|
||||
|
||||
+29
-13
@@ -279,19 +279,22 @@ type exportChannel struct {
|
||||
}
|
||||
|
||||
type exportStatusPage struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
Monitors []exportPageMember `json:"monitors"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
Groups []pageGroupView `json:"groups"`
|
||||
Monitors []exportPageMember `json:"monitors"`
|
||||
}
|
||||
|
||||
type exportPageMember struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Section string `json:"section"`
|
||||
Label string `json:"label"`
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
Section string `json:"section"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
type exportSSO struct {
|
||||
@@ -449,17 +452,30 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
}
|
||||
x.StatusPages = []exportStatusPage{}
|
||||
for _, pg := range pages {
|
||||
pgGroups, err := q.ListStatusPageGroups(ctx, pg.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exportedGroups := []pageGroupView{}
|
||||
newPageGroupTree(pgGroups).walk(func(g store.StatusPageGroup, _ int) {
|
||||
exportedGroups = append(exportedGroups, pageGroupView{
|
||||
ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position,
|
||||
})
|
||||
})
|
||||
pm, err := q.StatusPageMonitors(ctx, pg.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
members := []exportPageMember{}
|
||||
for _, m := range pm {
|
||||
members = append(members, exportPageMember{MonitorID: m.MonitorID, Section: m.Section, Label: m.Label})
|
||||
members = append(members, exportPageMember{
|
||||
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
|
||||
})
|
||||
}
|
||||
x.StatusPages = append(x.StatusPages, exportStatusPage{
|
||||
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description, Published: pg.Published,
|
||||
CustomDomain: pg.CustomDomain, Monitors: members,
|
||||
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
|
||||
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
|
||||
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -182,6 +182,11 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
page := org.Group("/statuspages/:id")
|
||||
page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
|
||||
page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
|
||||
page.GET("/groups", canPage(authz.StatusPagesRead), s.listStatusPageGroups)
|
||||
page.POST("/groups", canPage(authz.StatusPagesWrite), s.createStatusPageGroup)
|
||||
page.PUT("/groups/:group_id", canPage(authz.StatusPagesWrite), s.updateStatusPageGroup)
|
||||
page.DELETE("/groups/:group_id", canPage(authz.StatusPagesWrite), s.deleteStatusPageGroup)
|
||||
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
|
||||
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
|
||||
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
|
||||
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
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
|
||||
}
|
||||
+217
-34
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"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/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
@@ -42,17 +44,25 @@ var (
|
||||
// buildSnapshot computes what the public sees of page.
|
||||
func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) {
|
||||
snap := agentapi.PageSnapshot{
|
||||
Slug: page.Slug, Title: page.Title, Description: page.Description,
|
||||
Sections: []agentapi.Section{}, Incidents: []agentapi.PageIncident{}, GeneratedAt: time.Now(),
|
||||
Slug: page.Slug,
|
||||
Title: page.Title,
|
||||
Description: page.Description,
|
||||
ShowDetails: page.ShowComponentDetails,
|
||||
Sections: []agentapi.Section{},
|
||||
Incidents: []agentapi.PageIncident{},
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
_ = json.Unmarshal(page.Theme, &snap.Theme)
|
||||
var (
|
||||
listed []store.StatusPageMonitorsRow
|
||||
latest []store.LatestResultsRow
|
||||
open []store.Incident
|
||||
daily []store.DailyBucketsForMonitorsRow
|
||||
incidents []store.Incident
|
||||
planned map[uuid.UUID][]store.MaintenanceWindow
|
||||
listed []store.StatusPageMonitorsRow
|
||||
pageGroups []store.StatusPageGroup
|
||||
latest []store.LatestResultsRow
|
||||
open []store.Incident
|
||||
daily []store.DailyBucketsForMonitorsRow
|
||||
hourly []store.HourlyBucketsRow
|
||||
regions []store.Region
|
||||
incidents []store.Incident
|
||||
planned map[uuid.UUID][]store.MaintenanceWindow
|
||||
)
|
||||
now := time.Now()
|
||||
err := s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
@@ -60,6 +70,9 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
if listed, err = q.StatusPageMonitors(ctx, page.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if pageGroups, err = q.ListStatusPageGroups(ctx, page.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
ids := make([]uuid.UUID, len(listed))
|
||||
for i, m := range listed {
|
||||
ids[i] = m.MonitorID
|
||||
@@ -75,6 +88,16 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if page.ShowComponentDetails {
|
||||
if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{
|
||||
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -90,11 +113,13 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
}
|
||||
failing := map[uuid.UUID]int{}
|
||||
reported := map[uuid.UUID]int{}
|
||||
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
|
||||
for _, l := range latest {
|
||||
reported[l.MonitorID]++
|
||||
if !l.Ok {
|
||||
failing[l.MonitorID]++
|
||||
}
|
||||
latestByMonitor[l.MonitorID] = append(latestByMonitor[l.MonitorID], l)
|
||||
}
|
||||
down := map[uuid.UUID]bool{}
|
||||
for _, i := range open {
|
||||
@@ -104,15 +129,34 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
for _, d := range daily {
|
||||
days[d.MonitorID] = append(days[d.MonitorID], web.Bucket{Start: d.Bucket, Total: d.Total, OK: d.OkCount})
|
||||
}
|
||||
hourlyByMonitor := map[uuid.UUID][]web.Bucket{}
|
||||
for _, h := range hourly {
|
||||
hourlyByMonitor[h.MonitorID] = append(hourlyByMonitor[h.MonitorID], web.Bucket{
|
||||
Start: h.Bucket, Total: h.Total, OK: h.OkCount, Latency: h.AvgLatencyMs,
|
||||
})
|
||||
}
|
||||
regionNames := make(map[string]string, len(regions))
|
||||
for _, r := range regions {
|
||||
regionNames[r.ID.String()] = r.Name
|
||||
}
|
||||
|
||||
names := map[uuid.UUID]string{}
|
||||
var states []string
|
||||
var ungrouped []agentapi.Component
|
||||
byGroup := map[uuid.UUID][]agentapi.Component{}
|
||||
for _, m := range listed {
|
||||
name := m.Label
|
||||
if name == "" {
|
||||
name = m.MonitorName
|
||||
}
|
||||
names[m.MonitorID] = name
|
||||
comp := agentapi.Component{Name: name, Uptime: web.Uptime(days[m.MonitorID]), Days: dayHistory(days[m.MonitorID], now)}
|
||||
uptime90 := web.Uptime(days[m.MonitorID])
|
||||
comp := agentapi.Component{
|
||||
ID: m.MonitorID.String(),
|
||||
Name: name,
|
||||
Uptime: uptime90,
|
||||
Days: dayHistory(days[m.MonitorID], now),
|
||||
}
|
||||
switch {
|
||||
case down[m.MonitorID]:
|
||||
comp.Status = agentapi.PageOutage
|
||||
@@ -123,13 +167,27 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
default:
|
||||
comp.Status = agentapi.PageOperational
|
||||
}
|
||||
if page.ShowComponentDetails {
|
||||
comp.Details = buildComponentDetails(
|
||||
days[m.MonitorID],
|
||||
hourlyByMonitor[m.MonitorID],
|
||||
latestByMonitor[m.MonitorID],
|
||||
regionNames,
|
||||
uptime90,
|
||||
now,
|
||||
)
|
||||
}
|
||||
states = append(states, comp.Status)
|
||||
if n := len(snap.Sections); n == 0 || snap.Sections[n-1].Name != m.Section {
|
||||
snap.Sections = append(snap.Sections, agentapi.Section{Name: m.Section})
|
||||
if m.GroupID != nil {
|
||||
byGroup[*m.GroupID] = append(byGroup[*m.GroupID], comp)
|
||||
} else {
|
||||
ungrouped = append(ungrouped, comp)
|
||||
}
|
||||
last := &snap.Sections[len(snap.Sections)-1]
|
||||
last.Components = append(last.Components, comp)
|
||||
}
|
||||
if len(ungrouped) > 0 {
|
||||
snap.Sections = append(snap.Sections, agentapi.Section{Name: "", Components: ungrouped})
|
||||
}
|
||||
snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...)
|
||||
snap.Status = agentapi.Summarize(states)
|
||||
snap.Maintenance = pageMaintenance(planned, names, now)
|
||||
for _, i := range incidents {
|
||||
@@ -138,6 +196,102 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
// buildPageSections turns a status page's group tree and grouped components
|
||||
// into recursive public sections, omitting subtrees with no components.
|
||||
func buildPageSections(tree pageGroupTree, byGroup map[uuid.UUID][]agentapi.Component) []agentapi.Section {
|
||||
var build func(id uuid.UUID) (agentapi.Section, []string)
|
||||
build = func(id uuid.UUID) (agentapi.Section, []string) {
|
||||
g := tree.byID[id]
|
||||
sec := agentapi.Section{Name: g.Name, Components: byGroup[id]}
|
||||
var states []string
|
||||
for _, c := range sec.Components {
|
||||
states = append(states, c.Status)
|
||||
}
|
||||
sec.Total = len(sec.Components)
|
||||
for _, childID := range tree.children[id] {
|
||||
childSec, childStates := build(childID)
|
||||
if childSec.Total == 0 {
|
||||
continue
|
||||
}
|
||||
sec.Children = append(sec.Children, childSec)
|
||||
sec.Total += childSec.Total
|
||||
states = append(states, childStates...)
|
||||
}
|
||||
if sec.Total > 0 {
|
||||
sec.Status = agentapi.Summarize(states)
|
||||
}
|
||||
return sec, states
|
||||
}
|
||||
var out []agentapi.Section
|
||||
for _, rootID := range tree.roots {
|
||||
sec, _ := build(rootID)
|
||||
if sec.Total > 0 {
|
||||
out = append(out, sec)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func buildComponentDetails(
|
||||
daily []web.Bucket,
|
||||
hourly []web.Bucket,
|
||||
latest []store.LatestResultsRow,
|
||||
regionNames map[string]string,
|
||||
uptime90 float64,
|
||||
now time.Time,
|
||||
) *agentapi.ComponentDetails {
|
||||
since7d := now.UTC().AddDate(0, 0, -7)
|
||||
since30d := now.UTC().AddDate(0, 0, -30)
|
||||
var d7, d30 []web.Bucket
|
||||
for _, b := range daily {
|
||||
if !b.Start.Before(since30d) {
|
||||
d30 = append(d30, b)
|
||||
}
|
||||
if !b.Start.Before(since7d) {
|
||||
d7 = append(d7, b)
|
||||
}
|
||||
}
|
||||
byHour := make(map[int64]web.Bucket, len(hourly))
|
||||
for _, b := range hourly {
|
||||
byHour[web.AlignBucket(b.Start.UTC(), time.Hour).Unix()] = b
|
||||
}
|
||||
endHour := web.AlignBucket(now.UTC(), time.Hour)
|
||||
hours := make([]agentapi.HourBucket, 24)
|
||||
for i := range hours {
|
||||
ts := endHour.Add(-time.Duration(23-i) * time.Hour)
|
||||
hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1}
|
||||
if b, ok := byHour[ts.Unix()]; ok && b.Total > 0 {
|
||||
hours[i].Uptime = float64(b.OK) / float64(b.Total)
|
||||
hours[i].AvgLatencyMS = int(math.Round(float64(b.Latency)))
|
||||
}
|
||||
}
|
||||
regs := make([]agentapi.ComponentRegion, 0, len(latest))
|
||||
for _, l := range latest {
|
||||
name := regionNames[l.Region]
|
||||
if name == "" {
|
||||
name = l.Region
|
||||
}
|
||||
status := agentapi.PageOperational
|
||||
if !l.Ok {
|
||||
status = agentapi.PageOutage
|
||||
}
|
||||
var latency int
|
||||
if l.LatencyMs != nil && *l.LatencyMs > 0 {
|
||||
latency = int(*l.LatencyMs)
|
||||
}
|
||||
regs = append(regs, agentapi.ComponentRegion{Name: name, Status: status, LatencyMS: latency})
|
||||
}
|
||||
slices.SortFunc(regs, func(a, b agentapi.ComponentRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
return &agentapi.ComponentDetails{
|
||||
SLA24h: web.Uptime(hourly),
|
||||
SLA7d: web.Uptime(d7),
|
||||
SLA30d: web.Uptime(d30),
|
||||
SLA90d: uptime90,
|
||||
Hours: hours,
|
||||
Regions: regs,
|
||||
}
|
||||
}
|
||||
|
||||
func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day {
|
||||
byDay := map[string]web.Bucket{}
|
||||
for _, b := range buckets {
|
||||
@@ -192,11 +346,12 @@ func (s *Server) agentPage(c *gin.Context) {
|
||||
}
|
||||
|
||||
type statusPageRequest struct {
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
Title string `json:"title" binding:"required,max=200"`
|
||||
Description string `json:"description" binding:"max=10000"`
|
||||
Published bool `json:"published"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
Title string `json:"title" binding:"required,max=200"`
|
||||
Description string `json:"description" binding:"max=10000"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
}
|
||||
|
||||
func (r *statusPageRequest) normalize() string {
|
||||
@@ -226,14 +381,15 @@ func (r *statusPageRequest) normalize() string {
|
||||
}
|
||||
|
||||
type statusPageView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
DomainVerified bool `json:"domain_verified"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
DomainVerified bool `json:"domain_verified"`
|
||||
// DomainRecord is the TXT record that proves control of CustomDomain.
|
||||
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
|
||||
}
|
||||
@@ -246,7 +402,8 @@ type dnsRecord struct {
|
||||
|
||||
func viewStatusPage(p store.StatusPage) statusPageView {
|
||||
v := statusPageView{
|
||||
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description, Published: p.Published,
|
||||
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description,
|
||||
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails,
|
||||
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
|
||||
}
|
||||
_ = json.Unmarshal(p.Theme, &v.Theme)
|
||||
@@ -313,7 +470,8 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
var err error
|
||||
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
|
||||
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
|
||||
Published: req.Published, DomainToken: newDomainToken(), Theme: theme,
|
||||
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails,
|
||||
DomainToken: newDomainToken(), Theme: theme,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -351,7 +509,8 @@ func (s *Server) updateStatusPage(c *gin.Context) {
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{
|
||||
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description, Published: req.Published, Theme: theme,
|
||||
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description,
|
||||
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Theme: theme,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -389,9 +548,10 @@ func (s *Server) deleteStatusPage(c *gin.Context) {
|
||||
}
|
||||
|
||||
type pageMonitor struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id" binding:"required"`
|
||||
Section string `json:"section" binding:"max=100"`
|
||||
Label string `json:"label" binding:"max=200"`
|
||||
MonitorID uuid.UUID `json:"monitor_id" binding:"required"`
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
Section string `json:"section" binding:"max=100"`
|
||||
Label string `json:"label" binding:"max=200"`
|
||||
}
|
||||
|
||||
type pageMonitorsRequest struct {
|
||||
@@ -412,13 +572,33 @@ func (s *Server) setPageMonitors(c *gin.Context) {
|
||||
if _, err := q.GetStatusPage(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
existingGroups, err := q.ListStatusPageGroups(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
groupsByID := make(map[uuid.UUID]store.StatusPageGroup, len(existingGroups))
|
||||
topByName := map[string]store.StatusPageGroup{}
|
||||
var nextPos int32
|
||||
for _, g := range existingGroups {
|
||||
groupsByID[g.ID] = g
|
||||
if g.ParentID == nil {
|
||||
topByName[g.Name] = g
|
||||
if g.Position >= nextPos {
|
||||
nextPos = g.Position + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, m := range req.Monitors {
|
||||
err := q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{
|
||||
groupID, section, err := resolvePageMonitorGroup(ctx, q, id, p.Org.ID, m, groupsByID, topByName, &nextPos)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = q.AddStatusPageMonitor(ctx, store.AddStatusPageMonitorParams{
|
||||
PageID: id, MonitorID: m.MonitorID, OrgID: p.Org.ID,
|
||||
Section: strings.TrimSpace(m.Section), Label: strings.TrimSpace(m.Label), Position: int32(i),
|
||||
Section: section, GroupID: groupID, Label: strings.TrimSpace(m.Label), Position: int32(i),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -426,9 +606,12 @@ func (s *Server) setPageMonitors(c *gin.Context) {
|
||||
}
|
||||
return nil
|
||||
})
|
||||
var pgErr *pgconn.PgError
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case errors.As(err, &pgErr) && pgErr.Code == "23503" && strings.Contains(pgErr.ConstraintName, "group_id"):
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_group")
|
||||
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
|
||||
// Unknown monitors, monitors of other orgs and duplicates.
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
|
||||
@@ -213,3 +213,217 @@ func verifyDomain(t *testing.T, owner *browser, pageID string, record map[string
|
||||
st, body := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil)
|
||||
expect(t, "verify domain", st, body, http.StatusNoContent, "")
|
||||
}
|
||||
|
||||
func TestStatusPageGroupsAndDetails(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer up.Close()
|
||||
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer down.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("spg")+".test", uniq("spg-"))
|
||||
|
||||
// Create monitor groups to test importing the hierarchy later.
|
||||
st, mgRoot := owner.do("POST", "/api/v1/org/groups", map[string]any{"name": "Core"})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor root group = %d %v, want 201", st, mgRoot)
|
||||
}
|
||||
st, mgChild := owner.do("POST", "/api/v1/org/groups", map[string]any{
|
||||
"name": "Edge",
|
||||
"parent_id": mgRoot["id"],
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor child group = %d %v, want 201", st, mgChild)
|
||||
}
|
||||
|
||||
newMonitor := func(name, target string, groupID any) string {
|
||||
t.Helper()
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": name,
|
||||
"type": "http",
|
||||
"target": target,
|
||||
"interval_seconds": 60,
|
||||
"confirmations": 1,
|
||||
"regions": []string{region},
|
||||
"group_id": groupID,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor %q = %d %v, want 201", name, st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
webID := newMonitor("web", up.URL, mgChild["id"])
|
||||
apiID := newMonitor("api", down.URL, mgRoot["id"])
|
||||
|
||||
slug := uniq("nested-")
|
||||
st, pageBody := owner.do("POST", "/api/v1/org/statuspages", map[string]any{
|
||||
"slug": slug,
|
||||
"title": "Nested Status",
|
||||
"published": true,
|
||||
"show_component_details": false,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create status page = %d %v, want 201", st, pageBody)
|
||||
}
|
||||
pageID := pageBody["id"].(string)
|
||||
|
||||
// Nested status page groups CRUD + cycle & depth validation.
|
||||
st, gParent := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
|
||||
"name": "Platform",
|
||||
"position": 0,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create page parent group = %d %v, want 201", st, gParent)
|
||||
}
|
||||
parentID := gParent["id"].(string)
|
||||
|
||||
st, gChild := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups", map[string]any{
|
||||
"name": "Public Services",
|
||||
"parent_id": parentID,
|
||||
"position": 0,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create page child group = %d %v, want 201", st, gChild)
|
||||
}
|
||||
childID := gChild["id"].(string)
|
||||
|
||||
// Cycle rejection.
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/groups/"+parentID, map[string]any{
|
||||
"name": "Platform",
|
||||
"parent_id": childID,
|
||||
})
|
||||
expect(t, "group cycle", st, body, http.StatusUnprocessableEntity, "group_cycle")
|
||||
|
||||
// Assign monitors into nested groups.
|
||||
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{
|
||||
"monitors": []map[string]any{
|
||||
{"monitor_id": webID, "group_id": childID, "label": "Website"},
|
||||
{"monitor_id": apiID, "group_id": parentID, "label": "API"},
|
||||
},
|
||||
})
|
||||
expect(t, "assign grouped monitors", st, body, http.StatusNoContent, "")
|
||||
|
||||
waitFor(t, 10*time.Second, "incident for failing monitor", func() bool {
|
||||
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
return len(b["incidents"].([]any)) == 1
|
||||
})
|
||||
|
||||
platform := e.statuspageClient(t, nil)
|
||||
snap, err := platform.Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatalf("Page() error = %v", err)
|
||||
}
|
||||
if snap.ShowDetails {
|
||||
t.Fatalf("snap.ShowDetails = true, want false")
|
||||
}
|
||||
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Platform" ||
|
||||
snap.Sections[0].Total != 2 || snap.Sections[0].Status != agentapi.PageDegraded ||
|
||||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Public Services" ||
|
||||
snap.Sections[0].Children[0].Status != agentapi.PageOperational {
|
||||
t.Fatalf("nested sections = %+v, want Platform(degraded,2) -> Public Services(operational,1)", snap.Sections)
|
||||
}
|
||||
if snap.Sections[0].Components[0].Details != nil {
|
||||
t.Errorf("component Details populated when show_component_details=false")
|
||||
}
|
||||
|
||||
// Enable show_component_details and verify snapshot details & privacy.
|
||||
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{
|
||||
"slug": slug,
|
||||
"title": "Nested Status",
|
||||
"published": true,
|
||||
"show_component_details": true,
|
||||
})
|
||||
if st != http.StatusOK || body["show_component_details"] != true {
|
||||
t.Fatalf("enable show_component_details = %d %v, want 200 with true", st, body)
|
||||
}
|
||||
snap, err = platform.Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatalf("Page(with details) error = %v", err)
|
||||
}
|
||||
if !snap.ShowDetails {
|
||||
t.Fatalf("snap.ShowDetails = false, want true")
|
||||
}
|
||||
comp, ok := snap.ComponentByID(apiID)
|
||||
if !ok || comp.Details == nil {
|
||||
t.Fatalf("ComponentByID(%s) = (%+v, %t), want component with Details", apiID, comp, ok)
|
||||
}
|
||||
if len(comp.Details.Hours) != 24 || len(comp.Details.Regions) != 1 {
|
||||
t.Errorf("component details hours/regions = %d/%d, want 24/1", len(comp.Details.Hours), len(comp.Details.Regions))
|
||||
}
|
||||
raw, _ := json.Marshal(snap)
|
||||
for _, secret := range []string{up.URL, down.URL, "unexpected status", "HTTP 500"} {
|
||||
if strings.Contains(string(raw), secret) {
|
||||
t.Errorf("snapshot with details leaks %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify live status page server renders component detail page.
|
||||
cat, _ := i18n.Load()
|
||||
spSrv, err := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
|
||||
if err != nil {
|
||||
t.Fatalf("statuspage.New() error = %v", err)
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
spSrv.Mount(router)
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+slug+"/components/"+apiID, nil)
|
||||
req.Host = "status.test"
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "API") || !strings.Contains(rec.Body.String(), "Last 24 hours") {
|
||||
t.Errorf("GET detail page = %d, want 200 with component details", rec.Code)
|
||||
}
|
||||
|
||||
// Static export has no broken /components/ links and embeds inline details.
|
||||
resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export")
|
||||
if err != nil {
|
||||
t.Fatalf("export request error = %v", err)
|
||||
}
|
||||
exported, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || strings.Contains(string(exported), "/components/") || !strings.Contains(string(exported), "Show details") {
|
||||
t.Errorf("export status = %d, want inline details without /components/ links", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Delete child group: monitor moves up to parent group.
|
||||
st, body = owner.do("DELETE", "/api/v1/org/statuspages/"+pageID+"/groups/"+childID, nil)
|
||||
expect(t, "delete child group", st, body, http.StatusNoContent, "")
|
||||
snap, err = platform.Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatalf("Page(after delete) error = %v", err)
|
||||
}
|
||||
if len(snap.Sections) != 1 || len(snap.Sections[0].Components) != 2 || len(snap.Sections[0].Children) != 0 {
|
||||
t.Errorf("after deleting child group, sections = %+v, want 2 monitors under Platform", snap.Sections)
|
||||
}
|
||||
|
||||
// Import monitor groups copies Core -> Edge and re-assigns monitors.
|
||||
st, imported := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/groups/import", nil)
|
||||
if st != http.StatusOK || len(imported["groups"].([]any)) != 2 {
|
||||
t.Fatalf("import groups = %d %v, want 200 with 2 groups", st, imported)
|
||||
}
|
||||
snap, err = platform.Page(context.Background(), "", slug)
|
||||
if err != nil {
|
||||
t.Fatalf("Page(after import) error = %v", err)
|
||||
}
|
||||
if len(snap.Sections) != 1 || snap.Sections[0].Name != "Core" ||
|
||||
len(snap.Sections[0].Children) != 1 || snap.Sections[0].Children[0].Name != "Edge" {
|
||||
t.Errorf("imported sections = %+v, want Core -> Edge", snap.Sections)
|
||||
}
|
||||
|
||||
// Console editor shows new controls.
|
||||
st, _, html := owner.page("/statuspages/" + pageID)
|
||||
for _, want := range []string{`name="show_component_details"`, `/groups/import`, `data-field="group_id"`} {
|
||||
if st != http.StatusOK || !strings.Contains(html, want) {
|
||||
t.Errorf("editor HTML = %d, missing %q", st, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user