package api import ( "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. // 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" } return deref(i.Status) } type incidentUpdateView struct { ID uuid.UUID `json:"id"` Status string `json:"status"` 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"` Status string `json:"status"` 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) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return store.GetIncidentRow{}, nil, 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 { return err } updates, err = q.ListIncidentUpdates(ctx, id) return err }) if errors.Is(err, pgx.ErrNoRows) { fail(c, http.StatusNotFound, "not_found") return inc, nil, false } if err != nil { internalError(c, err) return inc, nil, false } return inc, updates, 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, } } func toIncidentDetail(inc store.GetIncidentRow, updates []store.ListIncidentUpdatesRow) incidentDetailView { v := incidentDetailView{ ID: inc.ID, MonitorID: inc.MonitorID, Monitor: inc.MonitorName, Title: inc.Title, Status: incidentStatus(incidentOf(inc)), StartedAt: inc.StartedAt, ResolvedAt: inc.ResolvedAt, Updates: []incidentUpdateView{}, } for _, u := range 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, }) } return v } func (s *Server) getIncident(c *gin.Context) { inc, updates, ok := s.loadIncident(c) if ok { c.JSON(http.StatusOK, toIncidentDetail(inc, updates)) } } // 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 } inc, _, ok := s.loadIncident(c) if !ok || !s.mayWriteIncident(c, 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)}) return err }); err != nil { internalError(c, err) return } auditDetail(c, "incident_id", inc.ID.String()) c.Status(http.StatusNoContent) } type incidentUpdateRequest struct { 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) if !slices.Contains(web.IncidentStatuses, req.Status) || req.Message == "" { fail(c, http.StatusUnprocessableEntity, "invalid_input") return } inc, _, ok := s.loadIncident(c) if !ok || !s.mayWriteIncident(c, 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: inc.ID, Status: req.Status, Message: req.Message, Public: public, AuthorID: author, }) if err != nil { return err } return q.RefreshIncidentStatus(ctx, inc.ID) }); err != nil { internalError(c, err) return } auditDetail(c, "incident_id", 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}) } func (s *Server) deleteIncidentUpdate(c *gin.Context) { update, err := uuid.Parse(c.Param("update")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } inc, _, ok := s.loadIncident(c) if !ok || !s.mayWriteIncident(c, 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 { return err } return q.RefreshIncidentStatus(ctx, inc.ID) }); err != nil { internalError(c, err) return } if n == 0 { fail(c, http.StatusNotFound, "not_found") return } auditDetail(c, "incident_id", 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) if !ok { return nil, errAborted } ctx := c.Request.Context() d, 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 } v := web.IncidentDetailView{ Row: d.incidentRow(incidentOf(inc), inc.MonitorName), CanWrite: canInGroup(p, authz.IncidentsWrite, t, 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 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, }}) } 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(v.Row.Status) 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 { return web.IncidentStatuses[0] } return web.IncidentStatuses[min(i+1, len(web.IncidentStatuses)-1)] }