package web import ( "fmt" "io/fs" "net/url" "strconv" "strings" "time" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" ) // PublicAssets decides how a public status page loads its stylesheet: // linked from the status page server or inlined for a static export. type PublicAssets struct { CSSHref string InlineCSS string // StaleSince, if set, tells visitors that live updates are unavailable // and the page shows the state of that moment. StaleSince time.Time // LegalBase prefixes links to legal documents served as Markdown, e.g. // "/acme/" or "/" on a custom domain. Empty leaves them out, as in a // single-file export, which can only link elsewhere. LegalBase string // ComponentBase prefixes links to component detail pages, e.g. "/acme/" // or "/". Empty in static single-file exports where subpages do not exist. ComponentBase string // Now is the moment the page shows, deciding which maintenance is in // progress. Now time.Time // NoRefresh leaves out the periodic reload, on pages with a form. NoRefresh bool // PageSize is how many of a section's own components the page lists // at a time; 0 lists all, as in a single-file export. PageSize int // Pages holds the zero-based page shown of the sections paged, by // their PublicSection.Key. Pages map[string]int // Query is what the visitor searched the components for; OnlyProblems // keeps those with an outage or degraded. Query string OnlyProblems bool } // PublicSection is a section of a status page as a request for it shows // it: the components of one page of the section's own, its status and // count those of the whole section. type PublicSection struct { Name string Status string Total int // Key identifies the section in the URLs paging it, e.g. "0.2". Key string Components []agentapi.Component Children []PublicSection // Page is the zero-based page of the section's own components shown, // of Pages. Page, Pages int } // ComponentView is what a request for a status page shows of its // components: every section paged on its own, filtered by a search and to // those with problems if the visitor asked. type ComponentView struct { Sections []PublicSection // Total counts all components, Matches those the filters leave and // Problems those with an outage or degraded. Total, Matches, Problems int Query string OnlyProblems bool base string size int pages map[string]int } // Filterable reports whether the page lists enough components to offer the // search and filter, or uses them. func (v ComponentView) Filterable() bool { return v.size > 0 && v.Total > v.size || v.Query != "" || v.OnlyProblems } // Filtered reports whether a search or filter is in use. func (v ComponentView) Filtered() bool { return v.Query != "" || v.OnlyProblems } // PageHref links page of the section key, keeping the other sections' pages // and the filters. func (v ComponentView) PageHref(key string, page int) string { q := url.Values{} if v.Query != "" { q.Set("q", v.Query) } if v.OnlyProblems { q.Set("problems", "1") } for k, p := range v.pages { if k != key && p > 0 { q.Set("p."+k, strconv.Itoa(p+1)) } } if page > 0 { q.Set("p."+key, strconv.Itoa(page+1)) } href := BackHref(v.base) if len(q) > 0 { href += "?" + q.Encode() } return href + "#g-" + key } // ResetHref links the page without search, filter and paging. func (v ComponentView) ResetHref() string { return BackHref(v.base) } // Problem reports whether a component counts as an outage for the filter. func Problem(c agentapi.Component) bool { return c.Status == agentapi.PageOutage || c.Status == agentapi.PageDegraded } // PublicComponents decides which components of sections a request for the // page shows, as a.Query, a.OnlyProblems and a.Pages ask. func PublicComponents(sections []agentapi.Section, a PublicAssets) ComponentView { v := ComponentView{ Query: strings.TrimSpace(a.Query), OnlyProblems: a.OnlyProblems, base: a.ComponentBase, size: a.PageSize, pages: a.Pages, } needle := strings.ToLower(v.Query) match := func(path []string, c agentapi.Component) bool { if v.OnlyProblems && !Problem(c) { return false } if needle == "" || strings.Contains(strings.ToLower(c.Name), needle) { return true } for _, p := range path { if strings.Contains(strings.ToLower(p), needle) { return true } } return false } filtered := v.Filtered() var walk func(sec agentapi.Section, key string, path []string) (PublicSection, bool) walk = func(sec agentapi.Section, key string, path []string) (PublicSection, bool) { ps := PublicSection{Name: sec.Name, Status: secStatusName(sec), Total: SectionTotal(sec), Key: key, Pages: 1} if sec.Name != "" { path = append(path, sec.Name) } var own []agentapi.Component for _, c := range sec.Components { v.Total++ if Problem(c) { v.Problems++ } if match(path, c) { own = append(own, c) } } v.Matches += len(own) if v.size > 0 && len(own) > v.size { ps.Pages = (len(own) + v.size - 1) / v.size ps.Page = min(max(v.pages[key], 0), ps.Pages-1) own = own[ps.Page*v.size : min((ps.Page+1)*v.size, len(own))] } ps.Components = own // Unnamed sections are top-level lists without children. if sec.Name != "" { for i, child := range sec.Children { if c, ok := walk(child, key+"."+strconv.Itoa(i), path); ok { ps.Children = append(ps.Children, c) } } } return ps, !filtered || len(ps.Components) > 0 || len(ps.Children) > 0 } for i, sec := range sections { if ps, ok := walk(sec, strconv.Itoa(i), nil); ok { v.Sections = append(v.Sections, ps) } } return v } // BarPath draws the bars of one status of a chart. type BarPath struct { Status Status D string } // BarPaths draws bars as one path per status instead of an element with a // tooltip each: status pages list thousands of components with 90 bars // each, and their detail pages have the tooltips. func BarPaths(bs []Bar, height int) []BarPath { var order []Status ds := map[Status]*strings.Builder{} h := strconv.Itoa(height) for i, b := range bs { d, ok := ds[b.Status] if !ok { d = &strings.Builder{} ds[b.Status] = d order = append(order, b.Status) } d.WriteString("M" + strconv.Itoa(i*4) + " 0h3v" + h + "h-3z") } out := make([]BarPath, 0, len(order)) for _, st := range order { out = append(out, BarPath{Status: st, D: ds[st].String()}) } return out } // NoticeForm is the button of a notice page that acts on a mailed link, // so mail scanners opening the link do not act on it themselves. type NoticeForm struct { Action, Token, Button string } // Markdown renders src for display, or returns "" when it cannot. func Markdown(src string) string { html, err := RenderMarkdown(src) if err != nil { return "" } return html } // StylesheetText returns the built stylesheet for inlining. func StylesheetText() (string, error) { b, err := fs.ReadFile(static, "static/dist/app.css") return string(b), err } // DayBars turns a component's 90-day history into bars. func DayBars(days []agentapi.Day) []Bar { out := make([]Bar, len(days)) for i, d := range days { if d.Uptime < 0 { out[i] = Bar{Status: StatusUnknown, Title: d.Date + " · –"} continue } out[i] = Bar{Status: ratioStatus(d.Uptime), Title: d.Date + " · " + Percent(d.Uptime)} } return out } // HourBars turns a component's 24-hour history into bars. func HourBars(hours []agentapi.HourBucket) []Bar { out := make([]Bar, len(hours)) for i, h := range hours { label := h.Time.UTC().Format("15:04") + " UTC" if h.Uptime < 0 { out[i] = Bar{Status: StatusUnknown, Title: label + " · –"} continue } title := label + " · " + Percent(h.Uptime) if h.AvgLatencyMS > 0 { title += fmt.Sprintf(" · %d ms", h.AvgLatencyMS) } out[i] = Bar{Status: ratioStatus(h.Uptime), Title: title} } return out } // HourLatency builds the SVG polyline for a component's 24-hour latency. func HourLatency(hours []agentapi.HourBucket, width, height int) LatencyLine { if len(hours) < 2 { return LatencyLine{Width: width, Height: height} } buckets := make([]Bucket, 0, len(hours)) for _, h := range hours { if h.Uptime < 0 || h.AvgLatencyMS <= 0 { continue } buckets = append(buckets, Bucket{Start: h.Time, Total: 1, OK: 1, Latency: float32(h.AvgLatencyMS)}) } return Latency(buckets, hours[0].Time, hours[len(hours)-1].Time, width, height) } // AvgLatencyText formats the mean latency across hourly buckets with data. func AvgLatencyText(hours []agentapi.HourBucket) string { var sum, count int for _, h := range hours { if h.Uptime >= 0 && h.AvgLatencyMS > 0 { sum += h.AvgLatencyMS count++ } } if count == 0 { return "–" } return strconv.Itoa(sum/count) + " ms" } // PageStatus maps a page state to the chart statuses used for colors. func PageStatus(s string) Status { switch s { case agentapi.PageOperational: return StatusUp case agentapi.PageDegraded: return StatusDegraded case agentapi.PageOutage: return StatusDown case agentapi.PageUnderMaintenance: return StatusMaintenance } return StatusUnknown } // SectionStatus returns a section's aggregated status, falling back to // summarizing its direct components for legacy cached snapshots. func SectionStatus(sec agentapi.Section) Status { if sec.Status != "" { return PageStatus(sec.Status) } states := make([]string, len(sec.Components)) for i, c := range sec.Components { states[i] = c.Status } return PageStatus(agentapi.Summarize(states)) } // SectionTotal returns the total component count in sec and its descendants. func SectionTotal(sec agentapi.Section) int { if sec.Total > 0 { return sec.Total } total := len(sec.Components) for _, child := range sec.Children { total += SectionTotal(child) } return total } // ComponentHref returns the detail link for comp when clickable details are // enabled on a live status page server, or "" otherwise. func ComponentHref(base string, comp agentapi.Component, showDetails bool) string { if !showDetails || base == "" || comp.ID == "" { return "" } return base + "components/" + comp.ID } // BackHref turns a page base prefix ("/acme/" or "/") into the page's root URL. func BackHref(base string) string { if base == "" || base == "/" { return "/" } return strings.TrimSuffix(base, "/") } // UptimeText formats a component's uptime ratio, or "–" without data. func UptimeText(r float64) string { if r < 0 { return "–" } return Percent(r) }