feat(statuspage): serve public status pages from api snapshots

Pages render without JavaScript, are matched by verified custom domain
or by slug, and stay available from a stale snapshot for ten minutes if
the API is unreachable. Snapshots contain no targets or error details.

Refs #21, #22

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 08:39:00 +01:00
1 parent d820547e8c
commit 2b72715a9d
8 files changed
+1017

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
// Package statuspage serves public status pages from snapshots fetched
// through the agent API. It keeps a short in-memory cache and keeps serving
// the last snapshot for a while if the API is unreachable, so a page stays
// up during the incidents it is meant to report.
package statuspage
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"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 = 30 * time.Second
staleFor = 10 * time.Minute
)
// 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
now func() time.Time
mu sync.Mutex
cache map[string]entry
}
type entry struct {
snap agentapi.PageSnapshot
missing bool
fetched time.Time
}
// New returns a Server. ownHosts lists the host names of the default
// domain, e.g. "status.example.com"; requests to other hosts are matched
// against verified custom domains.
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, ownHosts []string) *Server {
s := &Server{src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, now: time.Now, cache: map[string]entry{}}
for _, h := range ownHosts {
s.ownHosts[strings.ToLower(h)] = true
}
return s
}
// Mount registers the page routes.
func (s *Server) Mount(r *gin.Engine) {
r.NoRoute(s.serve)
}
// 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)
var key, slug string
switch {
case s.IsCustomDomain(host):
if c.Request.URL.Path != "/" {
c.Status(http.StatusNotFound)
return
}
key = "host:" + host
default:
slug = strings.Trim(c.Request.URL.Path, "/")
if slug == "" || strings.Contains(slug, "/") {
c.Status(http.StatusNotFound)
return
}
key = "slug:" + slug
host = ""
}
snap, ok := s.snapshot(c.Request.Context(), key, host, slug)
if !ok {
c.Status(http.StatusNotFound)
return
}
l := s.catalog.Match(c.GetHeader("Accept-Language"))
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
c.Header("Cache-Control", "public, max-age=30")
c.Header("Content-Language", l.Lang())
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}))
}
func (s *Server) snapshot(ctx context.Context, key, host, slug string) (agentapi.PageSnapshot, bool) {
now := s.now()
s.mu.Lock()
e, cached := s.cache[key]
s.mu.Unlock()
if cached && now.Sub(e.fetched) < freshFor {
return e.snap, !e.missing
}
snap, err := s.src.Page(ctx, host, slug)
switch {
case err == nil:
e = entry{snap: snap, fetched: now}
case errors.Is(err, agentapi.ErrNotFound):
e = entry{missing: true, fetched: now}
default:
if cached && now.Sub(e.fetched) < staleFor {
s.log.WarnContext(ctx, "serving stale status page", "page", key, "error", err)
return e.snap, !e.missing
}
s.log.ErrorContext(ctx, "fetching status page failed", "page", key, "error", err)
return agentapi.PageSnapshot{}, false
}
s.mu.Lock()
s.cache[key] = e
s.mu.Unlock()
return e.snap, !e.missing
}
+104
View File
@@ -0,0 +1,104 @@
package statuspage
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
type fakeSource struct {
calls int
err error
pages map[string]agentapi.PageSnapshot
}
func (f *fakeSource) Page(_ context.Context, host, slug string) (agentapi.PageSnapshot, error) {
f.calls++
if f.err != nil {
return agentapi.PageSnapshot{}, f.err
}
p, ok := f.pages[host+"|"+slug]
if !ok {
return p, agentapi.ErrNotFound
}
return p, nil
}
func newTest(t *testing.T) (*Server, *fakeSource, *gin.Engine, *time.Time) {
t.Helper()
cat, err := i18n.Load()
if err != nil {
t.Fatal(err)
}
src := &fakeSource{pages: map[string]agentapi.PageSnapshot{
"|acme": {Title: "Acme status", Status: agentapi.PageOperational},
"status.acme.test|": {Title: "Acme on own domain", Status: agentapi.PageOutage},
}}
s := New(src, cat, slog.New(slog.DiscardHandler), []string{"status.example.test"})
now := time.Now()
s.now = func() time.Time { return now }
gin.SetMode(gin.TestMode)
r := gin.New()
s.Mount(r)
return s, src, r, &now
}
func get(r http.Handler, host, path string) (int, string) {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Host = host
req.Header.Set("Accept-Language", "de")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
func TestRouting(t *testing.T) {
_, _, r, _ := newTest(t)
tests := []struct {
host, path string
want int
contains string
}{
{"status.example.test", "/acme", 200, "Acme status"},
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
{"status.example.test", "/missing", 404, ""},
{"status.example.test", "/", 404, ""},
{"status.acme.test", "/", 200, "Acme on own domain"},
{"status.acme.test", "/acme", 404, ""},
{"other.test", "/", 404, ""},
}
for _, tt := range tests {
code, body := get(r, tt.host, tt.path)
if code != tt.want || !strings.Contains(body, tt.contains) {
t.Errorf("GET %s%s = %d (contains %q: %t), want %d", tt.host, tt.path, code, tt.contains, strings.Contains(body, tt.contains), tt.want)
}
}
}
func TestCacheAndStaleFallback(t *testing.T) {
_, src, r, now := newTest(t)
get(r, "status.example.test", "/acme")
get(r, "status.example.test", "/acme")
if src.calls != 1 {
t.Errorf("source calls within freshness window = %d, want 1", src.calls)
}
src.err = errors.New("api down")
*now = now.Add(time.Minute)
if code, body := get(r, "status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") {
t.Errorf("GET with API down = %d, want stale page", code)
}
*now = now.Add(time.Hour)
if code, _ := get(r, "status.example.test", "/acme"); code != 404 {
t.Errorf("GET with API down long after = %d, want 404", code)
}
}