feat: own incident statuses with a color; incidents before maintenance
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m38s
ci / test (pull_request) Successful in 14m21s
ci / build (pull_request) Successful in 16m36s
ci / image (pull_request) Successful in 3m37s

Organizations add statuses of their own, with a name and a color, next
to the built-in ones (Settings, incident statuses; API under
/org/incident-statuses, managed with org.manage). Updates pick them by
ID; the console and status pages show them in their color. Renaming or
recoloring carries into the history; a status in use cannot be deleted
(409 status_in_use). API responses give status "custom" with status_id,
status_name and status_color.

Status pages now list recent incidents before planned maintenance.

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-23 23:49:58 +01:00
1 parent 43a04e99b1
commit 2409a919c3
26 files changed
+1257 -238

No files matched your search

+9 -1
View File
@@ -136,10 +136,18 @@ var endpoints = []endpoint{
{method: "PATCH", path: "/api/v1/org/incidents/:id", tag: "Monitors", summary: "Name an incident", perm: "incidents.write",
description: "The title status pages show; empty shows the monitor's name.", req: incidentTitleRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/org/incidents/:id/updates", tag: "Monitors", summary: "Post an update with a status", perm: "incidents.write",
description: "`message` is Markdown. `public` (default true) shows it on status pages; false keeps it an internal note. The update's status becomes the incident's.",
description: "`status` is a built-in status or the `id` of one of the organization's own. `message` is Markdown. `public` (default true) shows it on status pages; false keeps it an internal note. The update's status becomes the incident's.",
req: incidentUpdateRequest{}, resp: incidentUpdateView{}, status: http.StatusCreated},
{method: "DELETE", path: "/api/v1/org/incidents/:id/updates/:update", tag: "Monitors", summary: "Delete an update", perm: "incidents.write",
status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/incident-statuses", tag: "Monitors", summary: "List the organization's own incident statuses", perm: "incidents.read",
resp: obj{"statuses": []incidentStatusView{}}},
{method: "POST", path: "/api/v1/org/incident-statuses", tag: "Monitors", summary: "Add an incident status with a color", perm: "org.manage",
description: "`color` is `#rrggbb`. Updates use it by its `id` as `status`.", req: incidentStatusRequest{}, resp: incidentStatusView{}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/org/incident-statuses/:id", tag: "Monitors", summary: "Rename or recolor an incident status", perm: "org.manage",
description: "Applies to the history of incidents that used it too.", req: incidentStatusRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/org/incident-statuses/:id", tag: "Monitors", summary: "Delete an unused incident status", perm: "org.manage",
description: "`409 status_in_use` while updates use it.", status: http.StatusNoContent},
// Status pages
{method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}},
+3
View File
@@ -42,6 +42,9 @@ var auditActions = map[string]string{
"PATCH /api/v1/org/incidents/:id": "incident.title",
"POST /api/v1/org/incidents/:id/updates": "incident.update",
"DELETE /api/v1/org/incidents/:id/updates/:update": "incident.update_delete",
"POST /api/v1/org/incident-statuses": "incident_status.create",
"PUT /api/v1/org/incident-statuses/:id": "incident_status.update",
"DELETE /api/v1/org/incident-statuses/:id": "incident_status.delete",
"POST /api/v1/me/org": "",
"POST /api/v1/me/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable",
+14 -5
View File
@@ -290,9 +290,9 @@ type incidentView struct {
ResolvedAt *time.Time `json:"resolved_at"`
Cause map[string]string `json:"cause"`
Title string `json:"title"`
// Status is resolved once the monitor recovered, otherwise the status
// of the latest update, empty before the first.
Status string `json:"status"`
// The status is resolved once the monitor recovered, otherwise the
// status of the latest update, empty before the first.
statusFields
}
// incidentPage reads a page of incidents, newest first, of one monitor
@@ -333,16 +333,25 @@ func (s *Server) listIncidents(c *gin.Context) {
if !ok {
return
}
rows, info, err := s.incidentPage(c.Request.Context(), current(c), pg, monitor)
ctx := c.Request.Context()
rows, info, err := s.incidentPage(ctx, current(c), pg, monitor)
if err != nil {
internalError(c, err)
return
}
var statuses customStatuses
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
statuses, err = loadCustomStatuses(ctx, q)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]incidentView, len(rows))
for i, r := range rows {
out[i] = incidentView{
ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt,
Title: r.Title, Status: incidentStatus(store.Incident{ResolvedAt: r.ResolvedAt, Status: r.Status}),
Title: r.Title, statusFields: toStatusFields(statuses.of(store.Incident{ResolvedAt: r.ResolvedAt, Status: r.Status, StatusID: r.StatusID}), r.StatusID),
}
_ = json.Unmarshal(r.Cause, &out[i].Cause)
}
+8 -3
View File
@@ -212,6 +212,8 @@ type monitorData struct {
// firstRegion the same per region.
first map[uuid.UUID]time.Time
firstRegion map[uuid.UUID]map[string]time.Time
// statuses are the organization's own incident statuses.
statuses customStatuses
}
// loadFirstData finds when monitors and their regions first reported. The
@@ -333,6 +335,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil {
return err
}
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err
}
ids := make([]uuid.UUID, len(monitors))
for i, m := range monitors {
ids[i] = m.ID
@@ -533,7 +538,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
}
v.Incidents = append(v.Incidents, d.incidentRow(store.Incident{
ID: i.ID, OrgID: i.OrgID, MonitorID: i.MonitorID, StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: i.Cause,
Title: i.Title, Status: i.Status,
Title: i.Title, Status: i.Status, StatusID: i.StatusID,
}, m.Name))
}
page.TitleID = "console.monitors.title"
@@ -557,7 +562,7 @@ func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentR
row := web.IncidentRow{
ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor,
Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil,
Title: i.Title, Status: incidentStatus(i),
Title: i.Title, Status: d.statuses.of(i),
}
end := time.Now()
if i.ResolvedAt != nil {
@@ -908,7 +913,7 @@ func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me w
for i, r := range rows {
v.Rows[i] = d.incidentRow(store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause,
Title: r.Title, Status: r.Status,
Title: r.Title, Status: r.Status, StatusID: r.StatusID,
}, r.MonitorName)
}
if monitor != nil {
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"net/http"
"regexp"
"strings"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// An organization's own incident statuses, next to the built-in ones.
var hexColor = regexp.MustCompile(`^#[0-9a-f]{6}$`)
type incidentStatusRequest struct {
Name string `json:"name" binding:"required,max=40"`
Color string `json:"color" binding:"required,max=7"`
}
type incidentStatusView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
}
// validStatusRequest normalizes req and reports whether it is usable.
func validStatusRequest(c *gin.Context, req *incidentStatusRequest) bool {
req.Name, req.Color = strings.TrimSpace(req.Name), strings.ToLower(strings.TrimSpace(req.Color))
if req.Name == "" || !hexColor.MatchString(req.Color) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return false
}
return true
}
func (s *Server) listIncidentStatuses(c *gin.Context) {
ctx := c.Request.Context()
var rows []store.IncidentStatus
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidentStatuses(ctx)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]incidentStatusView, len(rows))
for i, r := range rows {
out[i] = incidentStatusView{ID: r.ID, Name: r.Name, Color: r.Color}
}
c.JSON(http.StatusOK, gin.H{"statuses": out})
}
func (s *Server) createIncidentStatus(c *gin.Context) {
var req incidentStatusRequest
if !bind(c, &req) || !validStatusRequest(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
var row store.IncidentStatus
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.CreateIncidentStatus(ctx, store.CreateIncidentStatusParams{OrgID: p.Org.ID, Name: req.Name, Color: req.Color})
return err
})
if isUniqueViolation(err, "incident_statuses_org_id_name_key") {
fail(c, http.StatusConflict, "status_name_taken")
return
}
if err != nil {
internalError(c, err)
return
}
auditDetail(c, "name", req.Name)
c.JSON(http.StatusCreated, incidentStatusView{ID: row.ID, Name: row.Name, Color: row.Color})
}
// updateIncidentStatus renames or recolors a status, also in the history
// of incidents that used it.
func (s *Server) updateIncidentStatus(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req incidentStatusRequest
if !bind(c, &req) || !validStatusRequest(c, &req) {
return
}
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
n, err = q.UpdateIncidentStatus(ctx, store.UpdateIncidentStatusParams{ID: id, Name: req.Name, Color: req.Color})
return err
})
switch {
case isUniqueViolation(err, "incident_statuses_org_id_name_key"):
fail(c, http.StatusConflict, "status_name_taken")
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
auditDetail(c, "name", req.Name)
c.Status(http.StatusNoContent)
}
}
// deleteIncidentStatus removes a status nobody used yet; history keeps
// the ones in use.
func (s *Server) deleteIncidentStatus(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
n, err = q.DeleteIncidentStatus(ctx, id)
return err
})
switch {
case isForeignKeyViolation(err):
fail(c, http.StatusConflict, "status_in_use")
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
c.Status(http.StatusNoContent)
}
}
func (s *Server) incidentStatusesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context()
var rows []store.IncidentStatus
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidentStatuses(ctx)
return err
}); err != nil {
return nil, err
}
v := make([]web.CustomIncidentStatus, len(rows))
for i, r := range rows {
v[i] = web.CustomIncidentStatus{ID: r.ID.String(), Name: r.Name, Color: r.Color}
}
return web.IncidentStatusesPage(page, me, v, p.Grants.Can(authz.OrgManage)), nil
}
+140 -62
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"errors"
"net/http"
"slices"
@@ -19,19 +20,63 @@ import (
// Incidents open and close with their monitor. People explain them with a
// title, a status and updates, public on status pages or internal notes.
// Statuses are the built-in ones or the organization's own, with a color.
// incidentStatus is what an incident shows: resolved once its monitor
// recovered, otherwise the status of its latest update, empty before one.
func incidentStatus(i store.Incident) string {
if i.ResolvedAt != nil {
return "resolved"
// customStatuses are an organization's own statuses by ID.
type customStatuses map[uuid.UUID]store.IncidentStatus
func loadCustomStatuses(ctx context.Context, q *store.Queries) (customStatuses, error) {
rows, err := q.ListIncidentStatuses(ctx)
out := customStatuses{}
for _, r := range rows {
out[r.ID] = r
}
return deref(i.Status)
return out, err
}
// info describes a stored status: a built-in key, or custom with the
// status named by id.
func (cs customStatuses) info(key *string, id *uuid.UUID) web.IncidentStatusInfo {
if key == nil {
return web.IncidentStatusInfo{}
}
if *key == "custom" && id != nil {
st := cs[*id]
return web.IncidentStatusInfo{Key: "custom", Name: st.Name, Color: st.Color}
}
return web.IncidentStatusInfo{Key: *key}
}
// of is what an incident shows: resolved once its monitor recovered,
// otherwise the status of its latest update, empty before one.
func (cs customStatuses) of(i store.Incident) web.IncidentStatusInfo {
if i.ResolvedAt != nil {
return web.IncidentStatusInfo{Key: "resolved"}
}
return cs.info(i.Status, i.StatusID)
}
// statusFields are a status in API responses.
type statusFields struct {
// Status is investigating, identified, monitoring, resolved or custom.
Status string `json:"status"`
// StatusID, StatusName and StatusColor describe a custom status.
StatusID *uuid.UUID `json:"status_id,omitempty"`
StatusName string `json:"status_name,omitempty"`
StatusColor string `json:"status_color,omitempty"`
}
func toStatusFields(info web.IncidentStatusInfo, id *uuid.UUID) statusFields {
f := statusFields{Status: info.Key}
if info.Key == "custom" {
f.StatusID, f.StatusName, f.StatusColor = id, info.Name, info.Color
}
return f
}
type incidentUpdateView struct {
ID uuid.UUID `json:"id"`
Status string `json:"status"`
ID uuid.UUID `json:"id"`
statusFields
Message string `json:"message"`
Public bool `json:"public"`
Author string `json:"author"`
@@ -39,72 +84,81 @@ type incidentUpdateView struct {
}
type incidentDetailView struct {
ID uuid.UUID `json:"id"`
MonitorID uuid.UUID `json:"monitor_id"`
Monitor string `json:"monitor"`
Title string `json:"title"`
Status string `json:"status"`
ID uuid.UUID `json:"id"`
MonitorID uuid.UUID `json:"monitor_id"`
Monitor string `json:"monitor"`
Title string `json:"title"`
statusFields
StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"`
Updates []incidentUpdateView `json:"updates"`
}
// loadIncident returns the incident of the request with its updates.
func (s *Server) loadIncident(c *gin.Context) (store.GetIncidentRow, []store.ListIncidentUpdatesRow, bool) {
// incidentData is an incident with its updates and the organization's
// statuses.
type incidentData struct {
inc store.GetIncidentRow
updates []store.ListIncidentUpdatesRow
statuses customStatuses
}
// loadIncident reads the incident of the request.
func (s *Server) loadIncident(c *gin.Context) (incidentData, bool) {
var d incidentData
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return store.GetIncidentRow{}, nil, false
return d, false
}
ctx := c.Request.Context()
var (
inc store.GetIncidentRow
updates []store.ListIncidentUpdatesRow
)
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
if inc, err = q.GetIncident(ctx, id); err != nil {
if d.inc, err = q.GetIncident(ctx, id); err != nil {
return err
}
updates, err = q.ListIncidentUpdates(ctx, id)
if d.updates, err = q.ListIncidentUpdates(ctx, id); err != nil {
return err
}
d.statuses, err = loadCustomStatuses(ctx, q)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return inc, nil, false
return d, false
}
if err != nil {
internalError(c, err)
return inc, nil, false
return d, false
}
return inc, updates, true
return d, true
}
func incidentOf(r store.GetIncidentRow) store.Incident {
return store.Incident{
ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt,
Cause: r.Cause, Title: r.Title, Status: r.Status,
Cause: r.Cause, Title: r.Title, Status: r.Status, StatusID: r.StatusID,
}
}
func toIncidentDetail(inc store.GetIncidentRow, updates []store.ListIncidentUpdatesRow) incidentDetailView {
func (d incidentData) view() incidentDetailView {
inc := incidentOf(d.inc)
v := incidentDetailView{
ID: inc.ID, MonitorID: inc.MonitorID, Monitor: inc.MonitorName, Title: inc.Title,
Status: incidentStatus(incidentOf(inc)), StartedAt: inc.StartedAt, ResolvedAt: inc.ResolvedAt,
ID: inc.ID, MonitorID: inc.MonitorID, Monitor: d.inc.MonitorName, Title: inc.Title,
statusFields: toStatusFields(d.statuses.of(inc), inc.StatusID), StartedAt: inc.StartedAt, ResolvedAt: inc.ResolvedAt,
Updates: []incidentUpdateView{},
}
for _, u := range updates {
for _, u := range d.updates {
v.Updates = append(v.Updates, incidentUpdateView{
ID: u.ID, Status: u.Status, Message: u.Message, Public: u.Public, Author: u.AuthorName, CreatedAt: u.CreatedAt,
ID: u.ID, statusFields: toStatusFields(d.statuses.info(&u.Status, u.StatusID), u.StatusID),
Message: u.Message, Public: u.Public, Author: u.AuthorName, CreatedAt: u.CreatedAt,
})
}
return v
}
func (s *Server) getIncident(c *gin.Context) {
inc, updates, ok := s.loadIncident(c)
if ok {
c.JSON(http.StatusOK, toIncidentDetail(inc, updates))
if d, ok := s.loadIncident(c); ok {
c.JSON(http.StatusOK, d.view())
}
}
@@ -135,23 +189,24 @@ func (s *Server) setIncidentTitle(c *gin.Context) {
if !bind(c, &req) {
return
}
inc, _, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, inc) {
d, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, d.inc) {
return
}
ctx := c.Request.Context()
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
_, err := q.SetIncidentTitle(ctx, store.SetIncidentTitleParams{ID: inc.ID, Title: strings.TrimSpace(req.Title)})
_, err := q.SetIncidentTitle(ctx, store.SetIncidentTitleParams{ID: d.inc.ID, Title: strings.TrimSpace(req.Title)})
return err
}); err != nil {
internalError(c, err)
return
}
auditDetail(c, "incident_id", inc.ID.String())
auditDetail(c, "incident_id", d.inc.ID.String())
c.Status(http.StatusNoContent)
}
type incidentUpdateRequest struct {
// Status is a built-in status or the ID of a custom one.
Status string `json:"status" binding:"required"`
Message string `json:"message" binding:"required,max=5000"`
// Public shows the update on status pages; otherwise it is an internal
@@ -166,12 +221,23 @@ func (s *Server) addIncidentUpdate(c *gin.Context) {
return
}
req.Message = strings.TrimSpace(req.Message)
if !slices.Contains(web.IncidentStatuses, req.Status) || req.Message == "" {
d, ok := s.loadIncident(c)
if !ok {
return
}
key, statusID := req.Status, (*uuid.UUID)(nil)
if id, err := uuid.Parse(req.Status); err == nil {
if _, ok := d.statuses[id]; !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
key, statusID = "custom", &id
}
if (statusID == nil && !slices.Contains(web.IncidentStatuses, key)) || req.Message == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
inc, _, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, inc) {
if !s.mayWriteIncident(c, d.inc) {
return
}
public := req.Public == nil || *req.Public
@@ -185,19 +251,22 @@ func (s *Server) addIncidentUpdate(c *gin.Context) {
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
u, err = q.AddIncidentUpdate(ctx, store.AddIncidentUpdateParams{
OrgID: p.Org.ID, IncidentID: inc.ID, Status: req.Status, Message: req.Message, Public: public, AuthorID: author,
OrgID: p.Org.ID, IncidentID: d.inc.ID, Status: key, StatusID: statusID, Message: req.Message, Public: public, AuthorID: author,
})
if err != nil {
return err
}
return q.RefreshIncidentStatus(ctx, inc.ID)
return q.RefreshIncidentStatus(ctx, d.inc.ID)
}); err != nil {
internalError(c, err)
return
}
auditDetail(c, "incident_id", inc.ID.String())
auditDetail(c, "incident_id", d.inc.ID.String())
auditDetail(c, "status", req.Status)
c.JSON(http.StatusCreated, incidentUpdateView{ID: u.ID, Status: u.Status, Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt})
c.JSON(http.StatusCreated, incidentUpdateView{
ID: u.ID, statusFields: toStatusFields(d.statuses.info(&u.Status, u.StatusID), u.StatusID),
Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt,
})
}
func (s *Server) deleteIncidentUpdate(c *gin.Context) {
@@ -206,18 +275,18 @@ func (s *Server) deleteIncidentUpdate(c *gin.Context) {
fail(c, http.StatusNotFound, "not_found")
return
}
inc, _, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, inc) {
d, ok := s.loadIncident(c)
if !ok || !s.mayWriteIncident(c, d.inc) {
return
}
ctx := c.Request.Context()
var n int64
if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
if n, err = q.DeleteIncidentUpdate(ctx, store.DeleteIncidentUpdateParams{ID: update, IncidentID: inc.ID}); err != nil || n == 0 {
if n, err = q.DeleteIncidentUpdate(ctx, store.DeleteIncidentUpdateParams{ID: update, IncidentID: d.inc.ID}); err != nil || n == 0 {
return err
}
return q.RefreshIncidentStatus(ctx, inc.ID)
return q.RefreshIncidentStatus(ctx, d.inc.ID)
}); err != nil {
internalError(c, err)
return
@@ -226,19 +295,19 @@ func (s *Server) deleteIncidentUpdate(c *gin.Context) {
fail(c, http.StatusNotFound, "not_found")
return
}
auditDetail(c, "incident_id", inc.ID.String())
auditDetail(c, "incident_id", d.inc.ID.String())
c.Status(http.StatusNoContent)
}
// incidentDetailView is the console page of one incident.
func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
c.Set(ctxPrincipal, p)
inc, updates, ok := s.loadIncident(c)
d, ok := s.loadIncident(c)
if !ok {
return nil, errAborted
}
ctx := c.Request.Context()
d, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
md, err := s.loadMonitorData(ctx, p, web.RangeByKey(""))
if err != nil {
return nil, err
}
@@ -246,9 +315,10 @@ func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page,
if err != nil {
return nil, err
}
inc := incidentOf(d.inc)
v := web.IncidentDetailView{
Row: d.incidentRow(incidentOf(inc), inc.MonitorName),
CanWrite: canInGroup(p, authz.IncidentsWrite, t, inc.MonitorGroupID),
Row: md.incidentRow(inc, d.inc.MonitorName),
CanWrite: canInGroup(p, authz.IncidentsWrite, t, d.inc.MonitorGroupID),
}
// Newest first; the monitor's own events among the updates.
type entry struct {
@@ -259,13 +329,14 @@ func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page,
if inc.ResolvedAt != nil {
entries = append(entries, entry{*inc.ResolvedAt, web.IncidentTimelineEntry{Kind: "resolved"}})
}
for _, u := range updates {
for _, u := range d.updates {
html, err := web.RenderMarkdown(u.Message)
if err != nil {
return nil, err
}
entries = append(entries, entry{u.CreatedAt, web.IncidentTimelineEntry{
Kind: "update", ID: u.ID.String(), Status: u.Status, HTML: html, Author: u.AuthorName, Public: u.Public,
Kind: "update", ID: u.ID.String(), Status: d.statuses.info(&u.Status, u.StatusID), HTML: html,
Author: u.AuthorName, Public: u.Public,
}})
}
slices.SortStableFunc(entries, func(a, b entry) int { return b.at.Compare(a.at) })
@@ -273,16 +344,23 @@ func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page,
x.e.At = x.at.UTC().Format(timeLayout)
v.Timeline = append(v.Timeline, x.e)
}
v.NextStatus = nextIncidentStatus(v.Row.Status)
v.NextStatus = nextIncidentStatus(inc)
for _, st := range d.statuses {
v.Custom = append(v.Custom, web.CustomIncidentStatus{ID: st.ID.String(), Name: st.Name, Color: st.Color})
}
slices.SortFunc(v.Custom, func(a, b web.CustomIncidentStatus) int { return strings.Compare(a.Name, b.Name) })
return web.IncidentDetailPage(page, me, v), nil
}
// nextIncidentStatus suggests the status after current: usually one step
// further, staying at resolved.
func nextIncidentStatus(current string) string {
i := slices.Index(web.IncidentStatuses, current)
if i < 0 {
// nextIncidentStatus suggests the status of the next update: one built-in
// step further, the same custom status, resolved at the end.
func nextIncidentStatus(inc store.Incident) string {
switch {
case inc.Status == nil:
return web.IncidentStatuses[0]
case *inc.Status == "custom" && inc.StatusID != nil:
return inc.StatusID.String()
}
i := slices.Index(web.IncidentStatuses, *inc.Status)
return web.IncidentStatuses[min(i+1, len(web.IncidentStatuses)-1)]
}
+72
View File
@@ -119,3 +119,75 @@ func TestIncidentUpdates(t *testing.T) {
t.Errorf("unknown incident = %d", st)
}
}
func TestCustomIncidentStatuses(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
owner := e.browser(t)
owner.signup("o@"+uniq("cis")+".test", uniq("cis-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "heartbeat", "interval_seconds": 3600})
monitorID := m["id"].(string)
slug := uniq("cisp-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme"})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Acme", "published": true})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}})
var incident uuid.UUID
if err := e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, cause)
SELECT org_id, id, now() - interval '10 minutes', '{}' FROM monitors WHERE id = $1 RETURNING id`, monitorID).Scan(&incident)
}); err != nil {
t.Fatal(err)
}
for _, bad := range []map[string]any{{"name": "x", "color": "red"}, {"name": " ", "color": "#7c3aed"}} {
st, body := owner.do("POST", "/api/v1/org/incident-statuses", bad)
expect(t, "invalid status", st, body, http.StatusUnprocessableEntity, "invalid_input")
}
st, status := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Waiting for provider", "color": "#7C3AED"})
if st != http.StatusCreated || status["color"] != "#7c3aed" {
t.Fatalf("create status = %d %v", st, status)
}
id := status["id"].(string)
st, body := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Waiting for provider", "color": "#000000"})
expect(t, "duplicate name", st, body, http.StatusConflict, "status_name_taken")
viewer := e.joinVia(t, owner.invite("v@"+uniq("cis")+".test", owner.roleID("viewer")))
st, body = viewer.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Mine", "color": "#000000"})
expect(t, "viewer adds a status", st, body, http.StatusForbidden, "forbidden")
// Updates use it by its ID; it shows with name and color.
base := "/api/v1/org/incidents/" + incident.String()
if st, body := owner.do("POST", base+"/updates", map[string]any{"status": id, "message": "Provider is on it."}); st != http.StatusCreated || body["status_name"] != "Waiting for provider" {
t.Fatalf("update with own status = %d %v", st, body)
}
st, body = owner.do("POST", base+"/updates", map[string]any{"status": uuid.NewString(), "message": "x"})
expect(t, "update with an unknown status", st, body, http.StatusUnprocessableEntity, "invalid_input")
if _, inc := owner.do("GET", base, nil); inc["status"] != "custom" || inc["status_id"] != id || inc["status_color"] != "#7c3aed" {
t.Errorf("incident = %v", inc)
}
snap, err := e.statuspageClient(t, nil).Page(ctx, "", slug)
if err != nil {
t.Fatal(err)
}
if len(snap.Incidents) == 0 || snap.Incidents[0].StatusName != "Waiting for provider" || snap.Incidents[0].Updates[0].StatusColor != "#7c3aed" {
t.Errorf("status page incidents = %+v", snap.Incidents)
}
_, _, html := owner.page("/incidents/" + incident.String())
if !strings.Contains(html, "background-color:#7c3aed") || !strings.Contains(html, `<option value="`+id+`" selected`) {
t.Error("the incident page lacks the own status or does not preselect it")
}
if _, _, html := owner.page("/settings/incident-statuses"); !strings.Contains(html, "Waiting for provider") || !strings.Contains(html, "Investigating") {
t.Error("the settings page lacks the statuses")
}
// Renaming carries into the history; a status in use stays.
owner.do("PUT", "/api/v1/org/incident-statuses/"+id, map[string]any{"name": "Provider working", "color": "#0ea5e9"})
if _, inc := owner.do("GET", base, nil); inc["status_name"] != "Provider working" {
t.Errorf("after renaming = %v", inc["status_name"])
}
st, body = owner.do("DELETE", "/api/v1/org/incident-statuses/"+id, nil)
expect(t, "delete a status in use", st, body, http.StatusConflict, "status_in_use")
_, unused := owner.do("POST", "/api/v1/org/incident-statuses", map[string]any{"name": "Unused", "color": "#111111"})
if st, _ := owner.do("DELETE", "/api/v1/org/incident-statuses/"+unused["id"].(string), nil); st != http.StatusNoContent {
t.Errorf("delete an unused status = %d", st)
}
}
+1
View File
@@ -48,6 +48,7 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/admin/legal", s.adminLegalPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/incidents/:id", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentDetailView))
r.GET("/settings/incident-statuses", s.orgPage("incident_statuses.title", authz.IncidentsRead, s.incidentStatusesView))
r.GET("/legal/:kind", s.legalPage)
r.GET("/consent", s.consentPage)
r.GET("/account/suspended", s.suspendedPage)
+4
View File
@@ -227,6 +227,10 @@ func (s *Server) Mount(r gin.IRouter) {
org.PATCH("/incidents/:id", s.setIncidentTitle)
org.POST("/incidents/:id/updates", s.addIncidentUpdate)
org.DELETE("/incidents/:id/updates/:update", s.deleteIncidentUpdate)
org.GET("/incident-statuses", can(authz.IncidentsRead), s.listIncidentStatuses)
org.POST("/incident-statuses", can(authz.OrgManage), s.createIncidentStatus)
org.PUT("/incident-statuses/:id", can(authz.OrgManage), s.updateIncidentStatus)
org.DELETE("/incident-statuses/:id", can(authz.OrgManage), s.deleteIncidentStatus)
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
+10 -2
View File
@@ -63,6 +63,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
regions []store.Region
incidents []store.Incident
updates []store.PublicIncidentUpdatesRow
statuses customStatuses
planned map[uuid.UUID][]store.MaintenanceWindow
)
now := time.Now()
@@ -109,6 +110,9 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
if updates, err = q.PublicIncidentUpdates(ctx, incidentIDs); err != nil {
return err
}
if statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err
}
if planned, err = maintenanceFor(ctx, q, ids); err != nil {
return err
}
@@ -201,12 +205,16 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
snap.Maintenance = pageMaintenance(planned, names, now)
updatesOf := map[uuid.UUID][]agentapi.PageIncidentUpdate{}
for _, u := range updates {
updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{Status: u.Status, Message: u.Message, At: u.CreatedAt})
st := statuses.info(&u.Status, u.StatusID)
updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{
Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Message: u.Message, At: u.CreatedAt,
})
}
for _, i := range incidents {
st := statuses.of(i)
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{
Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt,
Title: i.Title, Status: incidentStatus(i), Updates: updatesOf[i.ID],
Title: i.Title, Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Updates: updatesOf[i.ID],
})
}
return snap, nil