package api import ( "context" "errors" "net/http" "slices" "strings" "time" "github.com/a-h/templ" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) // 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. // 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 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"` statusFields Message string `json:"message"` Public bool `json:"public"` Author string `json:"author"` CreatedAt time.Time `json:"created_at"` } type incidentDetailView struct { 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"` } // 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 d, false } ctx := c.Request.Context() err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { var err error if d.inc, err = q.GetIncident(ctx, id); err != nil { return err } 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 d, false } if err != nil { internalError(c, err) return d, false } 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, StatusID: r.StatusID, } } func (d incidentData) view() incidentDetailView { inc := incidentOf(d.inc) v := incidentDetailView{ 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 d.updates { v.Updates = append(v.Updates, incidentUpdateView{ 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) { if d, ok := s.loadIncident(c); ok { c.JSON(http.StatusOK, d.view()) } } // mayWriteIncident checks incidents.write for the incident's monitor, // which roles limited to monitor groups grant too. func (s *Server) mayWriteIncident(c *gin.Context, inc store.GetIncidentRow) bool { p := current(c) t, err := s.loadGroupTree(c.Request.Context(), p.scope()) if err != nil { internalError(c, err) return false } if !canInGroup(p, authz.IncidentsWrite, t, inc.MonitorGroupID) { fail(c, http.StatusForbidden, "forbidden") return false } return true } type incidentTitleRequest struct { Title string `json:"title" binding:"max=200"` } // setIncidentTitle names the incident, e.g. on status pages; empty shows // the monitor's name. func (s *Server) setIncidentTitle(c *gin.Context) { var req incidentTitleRequest if !bind(c, &req) { return } 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: d.inc.ID, Title: strings.TrimSpace(req.Title)}) return err }); err != nil { internalError(c, err) return } 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 // note. Defaults to public. Public *bool `json:"public"` } // addIncidentUpdate tells what is going on: a status and a message. func (s *Server) addIncidentUpdate(c *gin.Context) { var req incidentUpdateRequest if !bind(c, &req) { return } req.Message = strings.TrimSpace(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 } if !s.mayWriteIncident(c, d.inc) { return } public := req.Public == nil || *req.Public p := current(c) var author *uuid.UUID if p.Session != nil { author = &p.UserID } ctx := c.Request.Context() var u store.IncidentUpdate 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: d.inc.ID, Status: key, StatusID: statusID, Message: req.Message, Public: public, AuthorID: author, }) if err != nil { return err } return q.RefreshIncidentStatus(ctx, d.inc.ID) }); err != nil { internalError(c, err) return } auditDetail(c, "incident_id", d.inc.ID.String()) auditDetail(c, "status", req.Status) 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) { update, err := uuid.Parse(c.Param("update")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } 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: d.inc.ID}); err != nil || n == 0 { return err } return q.RefreshIncidentStatus(ctx, d.inc.ID) }); err != nil { internalError(c, err) return } if n == 0 { fail(c, http.StatusNotFound, "not_found") return } 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) d, ok := s.loadIncident(c) if !ok { return nil, errAborted } ctx := c.Request.Context() md, err := s.loadMonitorData(ctx, p, web.RangeByKey("")) if err != nil { return nil, err } t, err := s.loadGroupTree(ctx, p.scope()) if err != nil { return nil, err } inc := incidentOf(d.inc) v := web.IncidentDetailView{ 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 { at time.Time e web.IncidentTimelineEntry } entries := []entry{{inc.StartedAt, web.IncidentTimelineEntry{Kind: "started"}}} if inc.ResolvedAt != nil { entries = append(entries, entry{*inc.ResolvedAt, web.IncidentTimelineEntry{Kind: "resolved"}}) } 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: 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) }) for _, x := range entries { x.e.At = x.at.UTC().Format(timeLayout) v.Timeline = append(v.Timeline, x.e) } 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 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)] }