Files
uptimesebi/internal/statuspage/statuspage.go
T
Sebastian UnterschützandClaude Opus 5.5 538c43b563
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m29s
ci / test (pull_request) Successful in 12m55s
ci / build (pull_request) Successful in 16m45s
ci / image (pull_request) Successful in 5m41s
feat(agents): talk to the API over a WebSocket and push page changes
Checkers and status page servers keep one WebSocket open to the API at
/agent/v1/stream and send their requests over it. The API answers them
through the agent API as if they had come over HTTP, each authenticated
again, so the protocol stays the same and a revoked token ends the
stream. While the stream is down agents fall back to plain HTTP, and an
API without it is asked again every five minutes.

Over the stream the API tells status page servers which of their pages
changed, so they fetch them at once instead of on their next refresh:
when a region of a monitor changes between up and down, an incident
opens or resolves, or anything of the organization is edited. Changes
are announced through Redis to every API instance and sent at most every
five seconds per stream. A page that changes while it is fetched is
fetched once more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 17:21:30 +01:00

547 lines
15 KiB
Go

// Package statuspage serves public status pages from snapshots fetched
// through the agent API.
//
// A status page has to stay up during the incidents it reports, including
// an outage of the API itself. Every snapshot is therefore kept in memory
// and on disk, requests are answered from that copy without waiting for the
// API, known pages are refreshed in the background, and the last known state
// is served for as long as the API stays unreachable, survives restarts and
// is marked as outdated once it ages. Only an explicit "not found" from the
// API removes a page.
package statuspage
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
const (
// freshFor is how long a snapshot is used without asking the API.
freshFor = 30 * time.Second
// refreshInterval is how often pages visited within recentFor are
// refreshed.
refreshInterval = 30 * time.Second
recentFor = 10 * time.Minute
// syncInterval is how often every page the API lists is fetched, so
// each one is cached before its first visit.
syncInterval = 5 * time.Minute
// staleNoticeAfter is when visitors are told the state may be outdated;
// a page nobody visited is up to syncInterval old.
staleNoticeAfter = 2 * syncInterval
// missFor is how long a host or slug without a page is answered
// without asking the API again.
missFor = time.Minute
maxMissing = 10_000
// refreshTimeout bounds fetching one page.
refreshTimeout = 30 * time.Second
// unknownPerSecond bounds the lookups of hosts and slugs that are
// neither cached nor known to be missing, so a flood of made-up names
// is not passed on to the API. Every page the API lists is cached by
// the sync, so known pages are not affected.
unknownPerSecond = 20
)
// Source fetches snapshots; *agentapi.Client implements it.
type Source interface {
// PageIfChanged answers agentapi.ErrNotModified when the page still
// has checksum.
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
Pages(ctx context.Context) ([]agentapi.PageRef, error)
}
// Server renders pages for one status page agent.
type Server struct {
src Source
catalog *i18n.Catalog
log *slog.Logger
// ownHosts are the hosts that serve pages by slug; any other host is
// looked up as a custom domain.
ownHosts map[string]bool
// dir persists snapshots; empty keeps them in memory only.
dir string
now func() time.Time
mu sync.Mutex
cache map[string]entry
refreshing map[string]bool
// again holds pages that changed while being refreshed, which are
// fetched once more.
again map[string]bool
// visited holds when each cached page was last visited.
visited map[string]time.Time
// missing holds when a key was last found to have no page.
missing map[string]time.Time
// unknownSecond and unknownCount count lookups passed on to the API in
// the current second.
unknownSecond int64
unknownCount int
// background tracks refreshes started by visits.
background sync.WaitGroup
}
// entry is one cached page, also its on-disk form.
type entry struct {
Key string `json:"key"`
Host string `json:"host,omitempty"`
Slug string `json:"slug,omitempty"`
Snap agentapi.PageSnapshot `json:"snapshot"`
Fetched time.Time `json:"fetched"`
// Checksum is the snapshot's, sent so the API can answer that nothing
// changed instead of sending it again.
Checksum string `json:"checksum,omitempty"`
}
// Options configure a Server.
type Options struct {
// Hosts are the host names of the default domain, e.g.
// "status.example.com"; requests to other hosts are matched against
// verified custom domains.
Hosts []string
// CacheDir persists snapshots across restarts. Empty disables
// persistence, which loses all pages on restart.
CacheDir string
}
// New returns a Server and loads snapshots persisted in o.CacheDir.
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
s := &Server{
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, again: map[string]bool{}, visited: map[string]time.Time{},
missing: map[string]time.Time{},
}
for _, h := range o.Hosts {
s.ownHosts[strings.ToLower(h)] = true
}
if s.dir != "" {
if err := os.MkdirAll(s.dir, 0o700); err != nil {
return nil, err
}
if err := s.loadDisk(); err != nil {
return nil, err
}
}
return s, nil
}
func (s *Server) loadDisk() error {
files, err := filepath.Glob(filepath.Join(s.dir, "*.json"))
if err != nil {
return err
}
for _, f := range files {
raw, err := os.ReadFile(f)
if err != nil {
return err
}
var e entry
if err := json.Unmarshal(raw, &e); err != nil || e.Key == "" {
s.log.Warn("ignoring unreadable cached page", "file", f, "error", err)
continue
}
s.cache[e.Key] = e
}
if len(s.cache) > 0 {
s.log.Info("loaded cached status pages", "count", len(s.cache))
}
return nil
}
func (s *Server) fileFor(key string) string {
sum := sha256.Sum256([]byte(key))
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
}
// persist writes atomically so a crash never leaves a truncated snapshot.
func (s *Server) persist(e entry) {
if s.dir == "" {
return
}
raw, err := json.Marshal(e)
if err == nil {
tmp := s.fileFor(e.Key) + ".tmp"
if err = os.WriteFile(tmp, raw, 0o600); err == nil {
err = os.Rename(tmp, s.fileFor(e.Key))
}
}
if err != nil {
s.log.Warn("persisting status page failed", "page", e.Key, "error", err)
}
}
func (s *Server) forget(key string) {
s.mu.Lock()
delete(s.cache, key)
delete(s.visited, key)
s.mu.Unlock()
if s.dir != "" {
_ = os.Remove(s.fileFor(key))
}
}
// Mount registers the page routes.
func (s *Server) Mount(r *gin.Engine) {
r.NoRoute(s.serve)
}
// Ready reports whether the server can answer visitors: either the API is
// reachable or pages are cached. A status page server must not drop out of
// the load balancer just because the API is down.
func (s *Server) Ready(ctx context.Context, apiProbe func(context.Context) error) error {
s.mu.Lock()
cached := len(s.cache)
s.mu.Unlock()
if cached > 0 {
return nil
}
return apiProbe(ctx)
}
// IsCustomDomain reports whether host is served as a custom domain.
func (s *Server) IsCustomDomain(host string) bool {
return !s.ownHosts[hostOnly(host)]
}
func hostOnly(h string) string {
if host, _, err := net.SplitHostPort(h); err == nil {
h = host
}
return strings.ToLower(strings.TrimSuffix(h, "."))
}
func (s *Server) serve(c *gin.Context) {
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
c.Status(http.StatusMethodNotAllowed)
return
}
host := hostOnly(c.Request.Host)
trimmed := strings.Trim(c.Request.URL.Path, "/")
parts := strings.Split(trimmed, "/")
var key, slug, base, legal, compID string
custom := s.IsCustomDomain(host)
switch {
case custom:
key, base = "host:"+host, "/"
switch {
case trimmed == "":
case len(parts) == 1:
legal = parts[0]
case len(parts) == 2 && parts[0] == "components" && parts[1] != "":
compID = parts[1]
default:
c.Status(http.StatusNotFound)
return
}
default:
slug = parts[0]
if slug == "" {
c.Status(http.StatusNotFound)
return
}
key, host, base = "slug:"+slug, "", "/"+slug+"/"
switch {
case len(parts) == 1:
case len(parts) == 2:
legal = parts[1]
case len(parts) == 3 && parts[1] == "components" && parts[2] != "":
compID = parts[2]
default:
c.Status(http.StatusNotFound)
return
}
}
e, ok := s.lookup(c.Request.Context(), key, host, slug)
if !ok {
c.Status(http.StatusNotFound)
return
}
if legal != "" {
s.serveLegal(c, e, legal, base)
return
}
var staleSince time.Time
if s.now().Sub(e.Fetched) > staleNoticeAfter {
staleSince = e.Fetched
}
assets := web.PublicAssets{
CSSHref: "/static/dist/app.css",
StaleSince: staleSince,
LegalBase: base,
ComponentBase: base,
Now: s.now(),
}
if compID != "" {
s.serveComponent(c, e, compID, assets)
return
}
s.localizeRequest(c)
c.Header("Cache-Control", "public, max-age=30")
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
}
// serveComponent renders one component's public detail page from the cached
// snapshot when the status page has enabled ShowDetails.
func (s *Server) serveComponent(c *gin.Context, e entry, compID string, assets web.PublicAssets) {
snap := e.Snap.WithMaintenance(assets.Now)
if !snap.ShowDetails {
c.Status(http.StatusNotFound)
return
}
comp, ok := snap.ComponentByID(compID)
if !ok {
c.Status(http.StatusNotFound)
return
}
s.localizeRequest(c)
c.Header("Cache-Control", "public, max-age=30")
web.Render(c, http.StatusOK, web.PublicComponentPage(snap, comp, assets))
}
// serveLegal shows a legal document of the page from the cached snapshot,
// so it stays reachable while the API is down.
func (s *Server) serveLegal(c *gin.Context, e entry, kind, base string) {
d, ok := e.Snap.LegalDocByKind(kind)
switch {
case !ok:
c.Status(http.StatusNotFound)
case d.URL != "":
c.Redirect(http.StatusFound, d.URL)
default:
html, err := web.RenderMarkdown(d.Markdown)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
s.localizeRequest(c)
c.Header("Cache-Control", "public, max-age=300")
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}, kind, html, base))
}
}
func (s *Server) localizeRequest(c *gin.Context) {
l := s.catalog.Match(c.GetHeader("Accept-Language"))
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
c.Header("Content-Language", l.Lang())
}
// lookup answers from the cache whenever possible and refreshes in the
// background; only unknown pages wait for the API.
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
now := s.now()
s.mu.Lock()
e, cached := s.cache[key]
if cached {
s.visited[key] = now
} else if !s.mayAsk(key, now) {
s.mu.Unlock()
return entry{}, false
}
s.mu.Unlock()
if cached {
if s.now().Sub(e.Fetched) >= freshFor {
s.background.Go(func() { s.refresh(context.WithoutCancel(ctx), key, host, slug) })
}
return e, true
}
e, ok := s.fetch(ctx, key, host, slug)
if ok {
s.mu.Lock()
s.visited[key] = now
s.mu.Unlock()
}
return e, ok
}
// mayAsk reports whether an uncached key may be looked up at the API: not
// when it was just found missing, nor beyond unknownPerSecond. s.mu is held.
func (s *Server) mayAsk(key string, now time.Time) bool {
if t, ok := s.missing[key]; ok && now.Sub(t) < missFor {
return false
}
if sec := now.Unix(); sec != s.unknownSecond {
s.unknownSecond, s.unknownCount = sec, 0
}
if s.unknownCount >= unknownPerSecond {
return false
}
s.unknownCount++
return true
}
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
s.mu.Lock()
old, known := s.cache[key]
s.mu.Unlock()
snap, err := s.src.PageIfChanged(ctx, host, slug, old.Checksum)
switch {
case errors.Is(err, agentapi.ErrNotModified) && known:
// Unchanged: the copy is current as of now.
old.Fetched = s.now()
old.Snap.GeneratedAt = old.Fetched
s.mu.Lock()
s.cache[key] = old
s.mu.Unlock()
s.persist(old)
return old, true
case errors.Is(err, agentapi.ErrNotFound):
s.forget(key)
s.mu.Lock()
if len(s.missing) >= maxMissing {
clear(s.missing)
}
s.missing[key] = s.now()
s.mu.Unlock()
return entry{}, false
case err != nil:
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
s.mu.Lock()
e, ok := s.cache[key]
s.mu.Unlock()
return e, ok
}
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
s.mu.Lock()
s.cache[key] = e
delete(s.missing, key)
s.mu.Unlock()
s.persist(e)
return e, true
}
// refresh fetches key unless another refresh of it is running, and once
// more if it changed meanwhile.
func (s *Server) refresh(ctx context.Context, key, host, slug string) {
s.mu.Lock()
if s.refreshing[key] {
s.mu.Unlock()
return
}
s.refreshing[key] = true
s.mu.Unlock()
for {
fctx, cancel := context.WithTimeout(ctx, refreshTimeout)
s.fetch(fctx, key, host, slug)
cancel()
s.mu.Lock()
again := s.again[key] && ctx.Err() == nil
delete(s.again, key)
if !again {
delete(s.refreshing, key)
s.mu.Unlock()
return
}
s.mu.Unlock()
}
}
// OnEvent handles the events the API sends over its stream: pages that
// changed are fetched at once instead of on their next refresh.
func (s *Server) OnEvent(event string, body []byte) {
if event != agentapi.EventPages {
return
}
var ev agentapi.PagesEvent
if err := json.Unmarshal(body, &ev); err != nil {
s.log.Warn("ignoring unreadable event", "event", event, "error", err)
return
}
for _, r := range ev.Pages {
s.changed("slug:"+r.Slug, "", r.Slug)
if r.Host != "" {
s.changed("host:"+r.Host, r.Host, "")
}
}
}
func (s *Server) changed(key, host, slug string) {
s.mu.Lock()
if s.refreshing[key] {
s.again[key] = true
s.mu.Unlock()
return
}
s.mu.Unlock()
s.background.Go(func() { s.refresh(context.Background(), key, host, slug) })
}
// Wait returns once the background refreshes started by visits are done.
func (s *Server) Wait() { s.background.Wait() }
// Run keeps pages fresh until ctx ends: every page the API lists every
// syncInterval, so all are cached before their first visit and survive an
// outage of the API, and recently visited ones every refreshInterval.
func (s *Server) Run(ctx context.Context) {
refresh := time.NewTicker(refreshInterval)
defer refresh.Stop()
listAll := time.NewTicker(syncInterval)
defer listAll.Stop()
s.Sync(ctx)
for {
select {
case <-ctx.Done():
return
case <-listAll.C:
s.Sync(ctx)
case <-refresh.C:
s.mu.Lock()
var recent []entry
for key, e := range s.cache {
if s.now().Sub(s.visited[key]) < recentFor {
recent = append(recent, e)
}
}
s.mu.Unlock()
for _, e := range recent {
s.refresh(ctx, e.Key, e.Host, e.Slug)
}
}
}
}
// Sync fetches every page the API lists and every cached one, which drops
// those the API no longer serves. While the API is unreachable the cache
// stays as it is.
func (s *Server) Sync(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, syncInterval)
defer cancel()
refs, err := s.src.Pages(ctx)
if err != nil {
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
return
}
todo := map[string]entry{}
s.mu.Lock()
for key, e := range s.cache {
todo[key] = e
}
s.mu.Unlock()
for _, r := range refs {
todo["slug:"+r.Slug] = entry{Key: "slug:" + r.Slug, Slug: r.Slug}
if r.Host != "" {
todo["host:"+r.Host] = entry{Key: "host:" + r.Host, Host: r.Host}
}
}
for _, e := range todo {
if ctx.Err() != nil {
return
}
s.refresh(ctx, e.Key, e.Host, e.Slug)
}
}