ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Canceled after 5m23s
ci / test (pull_request) Canceled after 5m23s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
A status page server only knew the pages visitors had asked it for, so during an API outage a server that had never seen a page could not serve it. The agent API now lists the pages a server serves (GET /agent/v1/pages/index), following the same rule as single pages, and status page servers fetch all of them on start and every five minutes, also dropping those no longer listed. Pages visited within the last ten minutes are still refreshed every 30 seconds; the outdated notice now appears after ten minutes, twice the sync interval. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
436 lines
12 KiB
Go
436 lines
12 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
|
|
)
|
|
|
|
// Source fetches snapshots; *agentapi.Client implements it.
|
|
type Source interface {
|
|
Page(ctx context.Context, host, slug 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
|
|
// visited holds when each page was last visited.
|
|
visited map[string]time.Time
|
|
// 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"`
|
|
}
|
|
|
|
// 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{}, visited: 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)
|
|
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) {
|
|
s.mu.Lock()
|
|
e, cached := s.cache[key]
|
|
s.visited[key] = s.now()
|
|
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
|
|
}
|
|
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)
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|