Monitors and groups get one-off or recurring maintenance. While it is in progress, failures neither open incidents nor alert, so the SLA is not affected; successes still resolve earlier incidents. The console shows monitors under maintenance and lists windows on a new page and on monitor pages. Status pages announce maintenance in progress and planned for the next two weeks and mark affected components; the occurrences are part of the snapshot and evaluated when the page is shown, so this also works from cache during an API outage. Maintenance and status page descriptions are rendered as Markdown. Closes #71 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
600 lines
17 KiB
Go
600 lines
17 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
|
"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/tenant"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
|
)
|
|
|
|
const (
|
|
historyDays = 90
|
|
incidentLookback = 14 * 24 * time.Hour
|
|
// verifyPrefix is the label under which customers publish the TXT record
|
|
// proving control of a custom domain.
|
|
verifyPrefix = "_uptimesebi."
|
|
)
|
|
|
|
var (
|
|
slugRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,62}$`)
|
|
accentRE = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
|
domainRE2 = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
|
|
)
|
|
|
|
// 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(),
|
|
}
|
|
_ = 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
|
|
)
|
|
now := time.Now()
|
|
err := s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
|
|
var err error
|
|
if listed, err = q.StatusPageMonitors(ctx, page.ID); err != nil {
|
|
return err
|
|
}
|
|
ids := make([]uuid.UUID, len(listed))
|
|
for i, m := range listed {
|
|
ids[i] = m.MonitorID
|
|
}
|
|
if latest, err = q.LatestResults(ctx, page.OrgID); err != nil {
|
|
return err
|
|
}
|
|
if open, err = q.OpenIncidents(ctx); err != nil {
|
|
return err
|
|
}
|
|
if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
|
|
OrgID: page.OrgID, Ids: ids, Bucket: now.AddDate(0, 0, -historyDays),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
|
|
return err
|
|
}
|
|
if planned, err = maintenanceFor(ctx, q, ids); err != nil {
|
|
return err
|
|
}
|
|
docs, err := q.LegalDocuments(ctx, &page.OrgID)
|
|
snap.Legal = mergeLegal(docs)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return snap, err
|
|
}
|
|
failing := map[uuid.UUID]int{}
|
|
reported := map[uuid.UUID]int{}
|
|
for _, l := range latest {
|
|
reported[l.MonitorID]++
|
|
if !l.Ok {
|
|
failing[l.MonitorID]++
|
|
}
|
|
}
|
|
down := map[uuid.UUID]bool{}
|
|
for _, i := range open {
|
|
down[i.MonitorID] = true
|
|
}
|
|
days := map[uuid.UUID][]web.Bucket{}
|
|
for _, d := range daily {
|
|
days[d.MonitorID] = append(days[d.MonitorID], web.Bucket{Start: d.Bucket, Total: d.Total, OK: d.OkCount})
|
|
}
|
|
names := map[uuid.UUID]string{}
|
|
var states []string
|
|
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)}
|
|
switch {
|
|
case down[m.MonitorID]:
|
|
comp.Status = agentapi.PageOutage
|
|
case !m.Enabled || reported[m.MonitorID] == 0:
|
|
comp.Status = agentapi.PageUnknown
|
|
case failing[m.MonitorID] > 0:
|
|
comp.Status = agentapi.PageDegraded
|
|
default:
|
|
comp.Status = agentapi.PageOperational
|
|
}
|
|
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})
|
|
}
|
|
last := &snap.Sections[len(snap.Sections)-1]
|
|
last.Components = append(last.Components, comp)
|
|
}
|
|
snap.Status = agentapi.Summarize(states)
|
|
snap.Maintenance = pageMaintenance(planned, names, now)
|
|
for _, i := range incidents {
|
|
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt})
|
|
}
|
|
return snap, nil
|
|
}
|
|
|
|
func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day {
|
|
byDay := map[string]web.Bucket{}
|
|
for _, b := range buckets {
|
|
byDay[b.Start.UTC().Format(time.DateOnly)] = b
|
|
}
|
|
out := make([]agentapi.Day, historyDays)
|
|
start := now.UTC().AddDate(0, 0, -(historyDays - 1))
|
|
for i := range out {
|
|
d := start.AddDate(0, 0, i).Format(time.DateOnly)
|
|
out[i] = agentapi.Day{Date: d, Uptime: -1}
|
|
if b, ok := byDay[d]; ok && b.Total > 0 {
|
|
out[i].Uptime = float64(b.OK) / float64(b.Total)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// agentPage serves a page snapshot to status page servers. Org-owned
|
|
// servers only receive their own org's pages.
|
|
func (s *Server) agentPage(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
var host, slug *string
|
|
if h := strings.ToLower(strings.TrimSpace(c.Query("host"))); h != "" {
|
|
host = &h
|
|
} else if sl := strings.ToLower(strings.TrimSpace(c.Query("slug"))); sl != "" {
|
|
slug = &sl
|
|
} else {
|
|
fail(c, http.StatusBadRequest, "invalid_input")
|
|
return
|
|
}
|
|
var page store.StatusPage
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
var err error
|
|
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
|
|
return err
|
|
})
|
|
a := agentOf(c)
|
|
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
snap, err := s.buildSnapshot(ctx, page)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, snap)
|
|
}
|
|
|
|
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"`
|
|
}
|
|
|
|
func (r *statusPageRequest) normalize() string {
|
|
r.Slug = strings.ToLower(strings.TrimSpace(r.Slug))
|
|
r.Title = strings.TrimSpace(r.Title)
|
|
r.Description = strings.TrimSpace(r.Description)
|
|
t := &r.Theme
|
|
t.Accent, t.LogoURL = strings.TrimSpace(t.Accent), strings.TrimSpace(t.LogoURL)
|
|
switch {
|
|
case !slugRE.MatchString(r.Slug):
|
|
return "invalid_slug"
|
|
case r.Title == "":
|
|
return "invalid_input"
|
|
case t.Accent != "" && !accentRE.MatchString(t.Accent):
|
|
return "invalid_theme"
|
|
case len(t.CSS) > 20000 || strings.Contains(t.CSS, "</"):
|
|
// The CSS is embedded in a <style> element; "</" could close it.
|
|
return "invalid_theme"
|
|
}
|
|
if t.LogoURL != "" {
|
|
u, err := url.Parse(t.LogoURL)
|
|
if err != nil || u.Scheme != "https" || u.Host == "" {
|
|
return "invalid_theme"
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
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"`
|
|
// DomainRecord is the TXT record that proves control of CustomDomain.
|
|
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
|
|
}
|
|
|
|
type dnsRecord struct {
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Value string `json:"value"`
|
|
}
|
|
|
|
func viewStatusPage(p store.StatusPage) statusPageView {
|
|
v := statusPageView{
|
|
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description, Published: p.Published,
|
|
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
|
|
}
|
|
_ = json.Unmarshal(p.Theme, &v.Theme)
|
|
if p.CustomDomain != nil {
|
|
v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken}
|
|
}
|
|
return v
|
|
}
|
|
|
|
// pageResource is the scope of assignments limited to one status page.
|
|
func pageResource(id uuid.UUID) authz.Resource {
|
|
return authz.Resource{Type: authz.StatusPage, ID: id}
|
|
}
|
|
|
|
// canPage aborts unless the principal holds perm for the page in :id,
|
|
// organization-wide or through an assignment scoped to that page.
|
|
func canPage(perm authz.Permission) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil || !current(c).Grants.Can(perm, pageResource(id)) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func (s *Server) listStatusPages(c *gin.Context) {
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var rows []store.StatusPage
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListStatusPages(ctx)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := []statusPageView{}
|
|
for _, r := range rows {
|
|
if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
|
|
out = append(out, viewStatusPage(r))
|
|
}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"pages": out})
|
|
}
|
|
|
|
func (s *Server) createStatusPage(c *gin.Context) {
|
|
var req statusPageRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
if code := req.normalize(); code != "" {
|
|
fail(c, http.StatusUnprocessableEntity, code)
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
theme, _ := json.Marshal(req.Theme)
|
|
var row store.StatusPage
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
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,
|
|
})
|
|
return err
|
|
})
|
|
if isUniqueViolation(err, "status_pages_slug_key") {
|
|
fail(c, http.StatusConflict, "slug_taken")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, viewStatusPage(row))
|
|
}
|
|
|
|
func newDomainToken() string {
|
|
b := make([]byte, 16)
|
|
_, _ = rand.Read(b)
|
|
return "uptimesebi-verify=" + hex.EncodeToString(b)
|
|
}
|
|
|
|
func (s *Server) updateStatusPage(c *gin.Context) {
|
|
var req statusPageRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
if code := req.normalize(); code != "" {
|
|
fail(c, http.StatusUnprocessableEntity, code)
|
|
return
|
|
}
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
theme, _ := json.Marshal(req.Theme)
|
|
var row store.StatusPage
|
|
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,
|
|
})
|
|
return err
|
|
})
|
|
switch {
|
|
case isUniqueViolation(err, "status_pages_slug_key"):
|
|
fail(c, http.StatusConflict, "slug_taken")
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
case err != nil:
|
|
internalError(c, err)
|
|
default:
|
|
c.JSON(http.StatusOK, viewStatusPage(row))
|
|
}
|
|
}
|
|
|
|
func (s *Server) deleteStatusPage(c *gin.Context) {
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var n int64
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
n, err = q.DeleteStatusPage(ctx, id)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if n == 0 {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
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"`
|
|
}
|
|
|
|
type pageMonitorsRequest struct {
|
|
Monitors []pageMonitor `json:"monitors" binding:"max=200,dive"`
|
|
}
|
|
|
|
// setPageMonitors replaces the page's components; their order is the
|
|
// display order.
|
|
func (s *Server) setPageMonitors(c *gin.Context) {
|
|
var req pageMonitorsRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
if _, err := q.GetStatusPage(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
for i, m := range req.Monitors {
|
|
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),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
|
|
// Unknown monitors, monitors of other orgs and duplicates.
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
|
|
case err != nil:
|
|
internalError(c, err)
|
|
default:
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
type domainRequest struct {
|
|
Domain string `json:"domain" binding:"max=253"`
|
|
}
|
|
|
|
func (s *Server) setPageDomain(c *gin.Context) {
|
|
var req domainRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
domain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Domain)), ".")
|
|
if domain != "" && !domainRE2.MatchString(domain) {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_domain")
|
|
return
|
|
}
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var row store.StatusPage
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
|
|
return err
|
|
})
|
|
switch {
|
|
case isUniqueViolation(err, "status_pages_custom_domain_key"):
|
|
fail(c, http.StatusConflict, "domain_taken")
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
case err != nil:
|
|
internalError(c, err)
|
|
default:
|
|
c.JSON(http.StatusOK, viewStatusPage(row))
|
|
}
|
|
}
|
|
|
|
// lookupTXT is replaced in tests.
|
|
var lookupTXT = net.DefaultResolver.LookupTXT
|
|
|
|
// verifyPageDomain checks the TXT record. Only verified domains are served,
|
|
// so nobody can claim a domain they do not control.
|
|
func (s *Server) verifyPageDomain(c *gin.Context) {
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
if !s.limit(c, "verify_domain:"+id.String(), 20, time.Hour) {
|
|
return
|
|
}
|
|
var row store.StatusPage
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.GetStatusPage(ctx, id)
|
|
return err
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if row.CustomDomain == nil {
|
|
fail(c, http.StatusConflict, "no_domain")
|
|
return
|
|
}
|
|
records, err := lookupTXT(ctx, verifyPrefix+*row.CustomDomain)
|
|
if err != nil || !slices.Contains(records, row.DomainToken) {
|
|
fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
|
|
return
|
|
}
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { return q.MarkDomainVerified(ctx, id) })
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
// exportStatusPage returns the page as one self-contained HTML file that
|
|
// can be hosted anywhere. It reflects the moment of export.
|
|
func (s *Server) exportStatusPage(c *gin.Context) {
|
|
id := uuid.MustParse(c.Param("id"))
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var row store.StatusPage
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.GetStatusPage(ctx, id)
|
|
return err
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
snap, err := s.buildSnapshot(ctx, row)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
css, err := web.StylesheetText()
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.Header("Content-Disposition", `attachment; filename="`+row.Slug+`.html"`)
|
|
web.Render(c, http.StatusOK, web.PublicStatusPage(snap.WithMaintenance(time.Now()), web.PublicAssets{InlineCSS: css, Now: time.Now()}))
|
|
}
|
|
|
|
// pageMaintenance lists the occurrences affecting the page's components
|
|
// from an hour ago, so a snapshot cached just before still knows about
|
|
// maintenance in progress, to two weeks ahead.
|
|
func pageMaintenance(planned map[uuid.UUID][]store.MaintenanceWindow, names map[uuid.UUID]string, now time.Time) []agentapi.PageMaintenance {
|
|
// Occurrences are matched by instant: time.Time values of the same
|
|
// instant differ as map keys when their locations were loaded apart.
|
|
type key struct {
|
|
window uuid.UUID
|
|
start int64
|
|
}
|
|
byKey := map[key]*agentapi.PageMaintenance{}
|
|
var order []key
|
|
for monitor, ws := range planned {
|
|
name, listed := names[monitor]
|
|
if !listed {
|
|
continue
|
|
}
|
|
for _, w := range ws {
|
|
for _, occ := range ruleOf(w).Occurrences(now.Add(-time.Hour), now.Add(upcomingHorizon)) {
|
|
k := key{w.ID, occ.Start.UnixNano()}
|
|
m, ok := byKey[k]
|
|
if !ok {
|
|
m = &agentapi.PageMaintenance{Title: w.Title, Description: w.Description, Start: occ.Start, End: occ.End}
|
|
byKey[k] = m
|
|
order = append(order, k)
|
|
}
|
|
if !slices.Contains(m.Components, name) {
|
|
m.Components = append(m.Components, name)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out := make([]agentapi.PageMaintenance, 0, len(order))
|
|
for _, k := range order {
|
|
m := *byKey[k]
|
|
slices.Sort(m.Components)
|
|
out = append(out, m)
|
|
}
|
|
slices.SortFunc(out, func(a, b agentapi.PageMaintenance) int {
|
|
if c := a.Start.Compare(b.Start); c != 0 {
|
|
return c
|
|
}
|
|
return strings.Compare(a.Title, b.Title)
|
|
})
|
|
return out
|
|
}
|