// 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 // staleNoticeAfter is when visitors are told the state may be outdated. staleNoticeAfter = 5 * time.Minute refreshInterval = 30 * time.Second ) // Source fetches snapshots; *agentapi.Client implements it. type Source interface { Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, 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 } // 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"` } // 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{}, } 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) 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) parts := strings.Split(strings.Trim(c.Request.URL.Path, "/"), "/") var key, slug, base, legal string custom := s.IsCustomDomain(host) switch { case custom: key, base = "host:"+host, "/" if len(parts) > 1 { c.Status(http.StatusNotFound) return } default: slug = parts[0] if len(parts) == 2 { legal = parts[1] } if slug == "" || len(parts) > 2 { c.Status(http.StatusNotFound) return } key, host, base = "slug:"+slug, "", "/"+slug+"/" } if custom { legal = parts[0] } 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 } s.localizeRequest(c) c.Header("Cache-Control", "public, max-age=30") web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), web.PublicAssets{CSSHref: "/static/dist/app.css", StaleSince: staleSince, LegalBase: base, Now: s.now()})) } // 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) { s.mu.Lock() e, cached := s.cache[key] s.mu.Unlock() if cached { if s.now().Sub(e.Fetched) >= freshFor { go s.refresh(context.WithoutCancel(ctx), key, host, slug) } return e, true } return s.fetch(ctx, key, host, slug) } func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) { snap, err := s.src.Page(ctx, host, slug) switch { case errors.Is(err, agentapi.ErrNotFound): s.forget(key) 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()} s.mu.Lock() s.cache[key] = e s.mu.Unlock() s.persist(e) return e, true } // refresh fetches key unless another refresh of it is running. 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() defer func() { s.mu.Lock() delete(s.refreshing, key) s.mu.Unlock() }() ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() s.fetch(ctx, key, host, slug) } // Run keeps every known page fresh until ctx ends, so pages stay current // even without visitors and the cache is warm when the API goes away. func (s *Server) Run(ctx context.Context) { tick := time.NewTicker(refreshInterval) defer tick.Stop() for { select { case <-ctx.Done(): return case <-tick.C: s.mu.Lock() entries := make([]entry, 0, len(s.cache)) for _, e := range s.cache { entries = append(entries, e) } s.mu.Unlock() for _, e := range entries { s.refresh(ctx, e.Key, e.Host, e.Slug) } } } }