From 4e9a198b2fd2ab2f6ad3a5e91daabace83a0a725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Tue, 24 Nov 2026 22:51:46 +0100 Subject: [PATCH] feat(statuspage): fetch every served page every five minutes 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 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- README.md | 2 +- internal/agentapi/pages.go | 17 ++++++ internal/api/agent.go | 1 + internal/api/statuspages.go | 20 +++++++ internal/api/statuspages_test.go | 14 ++++- internal/statuspage/statuspage.go | 76 ++++++++++++++++++++----- internal/statuspage/statuspage_test.go | 44 ++++++++++++++ internal/store/querier.go | 4 ++ internal/store/queries/status_pages.sql | 14 +++++ internal/store/status_pages.sql.go | 40 +++++++++++++ 10 files changed, 217 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index b696846..fbe0c22 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ Run as many API, checker and status page instances as you need; they share no lo | Hybrid | hosted | at the customer | at the customer | | Self-hosted | at the customer | at the customer | at the customer | -Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Once one of an organization's own status page servers has connected, only its own servers serve its pages; the platform's no longer do. +Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Status page servers fetch every page they serve every five minutes, so each one is cached before its first visit and keeps being served while the API is unreachable. Once one of an organization's own status page servers has connected, only its own servers serve its pages; the platform's no longer do. ## Usage diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go index d12b8ad..9b9a9eb 100644 --- a/internal/agentapi/pages.go +++ b/internal/agentapi/pages.go @@ -348,6 +348,23 @@ func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) { return LegalDoc{}, false } +// PageRef names a page a status page server serves: by Slug on its own +// hosts and, when Host is set, by that verified custom domain. +type PageRef struct { + Slug string `json:"slug"` + Host string `json:"host,omitempty"` +} + +// Pages lists every page this status page server serves, so it can keep +// them all cached before anyone visits. +func (c *Client) Pages(ctx context.Context) ([]PageRef, error) { + var out struct { + Pages []PageRef `json:"pages"` + } + err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out) + return out.Pages, err +} + // ErrNotFound means no published page matches. var ErrNotFound = errors.New("agentapi: not found") diff --git a/internal/api/agent.go b/internal/api/agent.go index d6a61b5..952df2d 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -41,6 +41,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) { g.GET("/update", s.agentUpdate) sp := g.Group("", requireAgentKind("statuspage")) sp.GET("/pages", s.agentPage) + sp.GET("/pages/index", s.agentPageIndex) sp.GET("/storage", s.storageGet) sp.PUT("/storage", s.storagePut) sp.DELETE("/storage", s.storageDelete) diff --git a/internal/api/statuspages.go b/internal/api/statuspages.go index 17cf843..aa974ca 100644 --- a/internal/api/statuspages.go +++ b/internal/api/statuspages.go @@ -377,6 +377,26 @@ func (s *Server) agentPage(c *gin.Context) { c.JSON(http.StatusOK, snap) } +// agentPageIndex lists the pages the status page server serves. +func (s *Server) agentPageIndex(c *gin.Context) { + ctx := c.Request.Context() + var rows []store.ServablePagesRow + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.ServablePages(ctx, agentOf(c).OrgID) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]agentapi.PageRef, len(rows)) + for i, r := range rows { + out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host} + } + c.JSON(http.StatusOK, gin.H{"pages": out}) +} + type statusPageRequest struct { Slug string `json:"slug" binding:"required,max=63"` Title string `json:"title" binding:"required,max=200"` diff --git a/internal/api/statuspages_test.go b/internal/api/statuspages_test.go index 3750ea5..6dca06c 100644 --- a/internal/api/statuspages_test.go +++ b/internal/api/statuspages_test.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" @@ -196,7 +197,15 @@ func TestStatusPages(t *testing.T) { t.Run("own servers replace the platform's", func(t *testing.T) { org := uuid.MustParse(owner.orgID()) own := e.statuspageClient(t, &org) - if _, err := platform.Page(context.Background(), "", slug); err != nil { + lists := func(c *agentapi.Client) bool { + t.Helper() + refs, err := c.Pages(context.Background()) + if err != nil { + t.Fatal(err) + } + return slices.ContainsFunc(refs, func(r agentapi.PageRef) bool { return r.Slug == slug && r.Host != "" }) + } + if _, err := platform.Page(context.Background(), "", slug); err != nil || !lists(platform) { t.Fatalf("platform server before the own one connected: %v", err) } if _, err := own.Hello(context.Background()); err != nil { @@ -208,6 +217,9 @@ func TestStatusPages(t *testing.T) { if snap, err := own.Page(context.Background(), "", slug); err != nil || snap.Title != "Acme Status" { t.Errorf("own server Page() = %v, %v", snap.Title, err) } + if lists(platform) || !lists(own) { + t.Error("the page lists do not follow who serves the page") + } if _, _, html := owner.page("/statuspages/" + pageID); !strings.Contains(html, "own status page servers serve its pages") { t.Error("the editor does not say who serves the pages") } diff --git a/internal/statuspage/statuspage.go b/internal/statuspage/statuspage.go index 362712f..353d983 100644 --- a/internal/statuspage/statuspage.go +++ b/internal/statuspage/statuspage.go @@ -35,14 +35,22 @@ import ( 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 + // 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. @@ -60,6 +68,8 @@ type Server struct { 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 } @@ -88,7 +98,7 @@ type Options struct { 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{}, + 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 @@ -308,6 +318,7 @@ func (s *Server) localizeRequest(c *gin.Context) { 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 { @@ -361,25 +372,64 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) { // Wait returns once the background refreshes started by visits are done. func (s *Server) Wait() { s.background.Wait() } -// 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. +// 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) { - tick := time.NewTicker(refreshInterval) - defer tick.Stop() + refresh := time.NewTicker(refreshInterval) + defer refresh.Stop() + listAll := time.NewTicker(syncInterval) + defer listAll.Stop() + s.Sync(ctx) for { select { case <-ctx.Done(): return - case <-tick.C: + case <-listAll.C: + s.Sync(ctx) + case <-refresh.C: s.mu.Lock() - entries := make([]entry, 0, len(s.cache)) - for _, e := range s.cache { - entries = append(entries, e) + 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 entries { + 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) + } +} diff --git a/internal/statuspage/statuspage_test.go b/internal/statuspage/statuspage_test.go index 89178e6..38e413b 100644 --- a/internal/statuspage/statuspage_test.go +++ b/internal/statuspage/statuspage_test.go @@ -49,6 +49,21 @@ func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.Page return p, nil } +// Pages lists the fake's pages by their keys: "host|" or "|slug". +func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.err != nil { + return nil, f.err + } + var out []agentapi.PageRef + for k := range f.pages { + host, slug, _ := strings.Cut(k, "|") + out = append(out, agentapi.PageRef{Host: host, Slug: slug}) + } + return out, nil +} + func (f *fakeSource) set(fn func(*fakeSource)) { f.mu.Lock() defer f.mu.Unlock() @@ -464,3 +479,32 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) { } }) } + +func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) { + dir := t.TempDir() + now := time.Now() + src := newSource() + h := newHarness(t, src, dir, &now) + h.srv.Sync(context.Background()) + + // Nobody visited them, yet both survive an outage and a restart. + now = now.Add(syncInterval) + restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now) + if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") { + t.Errorf("GET of a synced page with the API down = %d, want it without stale notice", code) + } + if code, body := restarted.get("status.acme.test", "/"); code != 200 || !strings.Contains(body, "Acme on own domain") { + t.Errorf("GET of a synced custom domain with the API down = %d", code) + } + restarted.srv.Sync(context.Background()) + if code, _ := restarted.get("status.example.test", "/acme"); code != 200 { + t.Errorf("a failed sync dropped the cache: %d", code) + } + + // A page the API no longer lists is dropped by the next sync. + src.set(func(f *fakeSource) { delete(f.pages, "|acme") }) + h.srv.Sync(context.Background()) + if code, _ := h.get("status.example.test", "/acme"); code != 404 { + t.Errorf("GET after the page left the list = %d, want 404", code) + } +} diff --git a/internal/store/querier.go b/internal/store/querier.go index 44654c6..87e0633 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -337,6 +337,10 @@ type Querier interface { // page from a keyset cursor whose string key is monitor and region. ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error) ScrubAuditEmail(ctx context.Context, email string) error + // System scope: the published pages a status page server serves, those + // of agent_org for an organization's server; the platform's leave the + // pages of organizations serving their own. + ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error) SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error) SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error) SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error diff --git a/internal/store/queries/status_pages.sql b/internal/store/queries/status_pages.sql index e64caa6..3ae6067 100644 --- a/internal/store/queries/status_pages.sql +++ b/internal/store/queries/status_pages.sql @@ -93,3 +93,17 @@ WHERE published AND suspended_at IS NULL AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL) AND ((sqlc.narg(host)::citext IS NOT NULL AND custom_domain = sqlc.narg(host) AND domain_verified_at IS NOT NULL) OR (sqlc.narg(slug)::citext IS NOT NULL AND slug = sqlc.narg(slug))); + +-- name: ServablePages :many +-- System scope: the published pages a status page server serves, those +-- of agent_org for an organization's server; the platform's leave the +-- pages of organizations serving their own. +SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host +FROM status_pages p +JOIN orgs o ON o.id = p.org_id +WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL + AND CASE WHEN sqlc.narg(agent_org)::uuid IS NULL + THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL) + ELSE p.org_id = sqlc.narg(agent_org)::uuid + END +ORDER BY p.slug; diff --git a/internal/store/status_pages.sql.go b/internal/store/status_pages.sql.go index eb55da7..c3919f1 100644 --- a/internal/store/status_pages.sql.go +++ b/internal/store/status_pages.sql.go @@ -352,6 +352,46 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar return err } +const servablePages = `-- name: ServablePages :many +SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host +FROM status_pages p +JOIN orgs o ON o.id = p.org_id +WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL + AND CASE WHEN $1::uuid IS NULL + THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL) + ELSE p.org_id = $1::uuid + END +ORDER BY p.slug +` + +type ServablePagesRow struct { + Slug string + Host string +} + +// System scope: the published pages a status page server serves, those +// of agent_org for an organization's server; the platform's leave the +// pages of organizations serving their own. +func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error) { + rows, err := q.db.Query(ctx, servablePages, agentOrg) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ServablePagesRow{} + for rows.Next() { + var i ServablePagesRow + if err := rows.Scan(&i.Slug, &i.Host); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const setStatusPageDomain = `-- name: SetStatusPageDomain :one UPDATE status_pages SET custom_domain = $1,