From fcf615dce7879287fa63c7740c9c03bd34b7a6f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Tue, 24 Nov 2026 22:57:22 +0100 Subject: [PATCH] feat(statuspage): refresh pages by checksum Each refresh sent the whole page again even when nothing had changed. Status page servers now send the checksum of their copy (If-None-Match) and the API answers 304 when the page, leaving out when it was generated, is unchanged; the server then only marks its copy current. The checksum is kept on disk with the page, so it survives restarts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/agentapi/agentapi.go | 10 +++++ internal/agentapi/pages.go | 26 +++++++++++- internal/api/statuspages.go | 8 ++++ internal/api/statuspages_test.go | 6 +++ internal/statuspage/statuspage.go | 23 +++++++++-- internal/statuspage/statuspage_test.go | 55 ++++++++++++++++++++++++-- 6 files changed, 120 insertions(+), 8 deletions(-) diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go index de1f5ea..83ed4f1 100644 --- a/internal/agentapi/agentapi.go +++ b/internal/agentapi/agentapi.go @@ -125,6 +125,11 @@ func (c *Client) WithHTTPClient(hc *http.Client) *Client { func (c *Client) Instance() uuid.UUID { return c.instance } func (c *Client) do(ctx context.Context, method, path string, in, out any) error { + return c.doWith(ctx, method, path, nil, in, out) +} + +// doWith is do with extra request headers. +func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error { var body io.Reader if in != nil { b, err := json.Marshal(in) @@ -142,6 +147,9 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error req.Header.Set(VersionHeader, fmt.Sprint(Version)) req.Header.Set(InstanceHeader, c.instance.String()) req.Header.Set(ReleaseHeader, c.release) + for k, v := range header { + req.Header[k] = v + } resp, err := c.hc.Do(req) if err != nil { return err @@ -152,6 +160,8 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error return ErrUnauthorized case resp.StatusCode == http.StatusNotFound: return ErrNotFound + case resp.StatusCode == http.StatusNotModified: + return ErrNotModified case resp.StatusCode >= 300: msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg)) diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go index 9b9a9eb..badb1b3 100644 --- a/internal/agentapi/pages.go +++ b/internal/agentapi/pages.go @@ -2,6 +2,9 @@ package agentapi import ( "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" "errors" "net/http" "net/url" @@ -368,16 +371,37 @@ func (c *Client) Pages(ctx context.Context) ([]PageRef, error) { // ErrNotFound means no published page matches. var ErrNotFound = errors.New("agentapi: not found") +// ErrNotModified means the page still matches the checksum sent. +var ErrNotModified = errors.New("agentapi: not modified") + +// Checksum identifies the content of s, leaving out when it was generated. +func (s PageSnapshot) Checksum() string { + s.GeneratedAt = time.Time{} + raw, _ := json.Marshal(s) + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + // Page fetches the published page for a custom domain host, or for slug if // host is empty. func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) { + return c.PageIfChanged(ctx, host, slug, "") +} + +// PageIfChanged is Page, but answers ErrNotModified instead of sending the +// page again when it still has the checksum given. +func (c *Client) PageIfChanged(ctx context.Context, host, slug, checksum string) (PageSnapshot, error) { q := url.Values{} if host != "" { q.Set("host", host) } else { q.Set("slug", slug) } + var h http.Header + if checksum != "" { + h = http.Header{"If-None-Match": {`"` + checksum + `"`}} + } var p PageSnapshot - err := c.do(ctx, http.MethodGet, "/pages?"+q.Encode(), nil, &p) + err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p) return p, err } diff --git a/internal/api/statuspages.go b/internal/api/statuspages.go index aa974ca..532c1dc 100644 --- a/internal/api/statuspages.go +++ b/internal/api/statuspages.go @@ -374,6 +374,14 @@ func (s *Server) agentPage(c *gin.Context) { internalError(c, err) return } + // The server sends the checksum of its copy; an unchanged page is not + // sent again. + etag := `"` + snap.Checksum() + `"` + c.Header("ETag", etag) + if c.GetHeader("If-None-Match") == etag { + c.Status(http.StatusNotModified) + return + } c.JSON(http.StatusOK, snap) } diff --git a/internal/api/statuspages_test.go b/internal/api/statuspages_test.go index 6dca06c..b96b49e 100644 --- a/internal/api/statuspages_test.go +++ b/internal/api/statuspages_test.go @@ -96,6 +96,12 @@ func TestStatusPages(t *testing.T) { snap.Sections[1].Components[0].Name != "Public API" { t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap) } + if _, err := platform.PageIfChanged(context.Background(), "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) { + t.Errorf("PageIfChanged(current checksum) error = %v, want not modified", err) + } + if again, err := platform.PageIfChanged(context.Background(), "", slug, "stale"); err != nil || again.Title != "Acme Status" { + t.Errorf("PageIfChanged(stale checksum) = %v, %v", again.Title, err) + } raw, _ := json.Marshal(snap) for _, secret := range []string{up.URL, down.URL, "unexpected status"} { if strings.Contains(string(raw), secret) { diff --git a/internal/statuspage/statuspage.go b/internal/statuspage/statuspage.go index 353d983..48b56db 100644 --- a/internal/statuspage/statuspage.go +++ b/internal/statuspage/statuspage.go @@ -49,7 +49,9 @@ const ( // Source fetches snapshots; *agentapi.Client implements it. type Source interface { - Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) + // 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) } @@ -81,6 +83,9 @@ type entry struct { 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. @@ -330,8 +335,20 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo } func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) { - snap, err := s.src.Page(ctx, host, slug) + 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) return entry{}, false @@ -342,7 +359,7 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool s.mu.Unlock() return e, ok } - e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now()} + e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()} s.mu.Lock() s.cache[key] = e s.mu.Unlock() diff --git a/internal/statuspage/statuspage_test.go b/internal/statuspage/statuspage_test.go index 38e413b..84471c0 100644 --- a/internal/statuspage/statuspage_test.go +++ b/internal/statuspage/statuspage_test.go @@ -20,12 +20,27 @@ import ( type fakeSource struct { mu sync.Mutex calls int - err error - delay time.Duration - pages map[string]agentapi.PageSnapshot + // unchanged counts the answers that the page had not changed. + unchanged int + err error + delay time.Duration + pages map[string]agentapi.PageSnapshot } -func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) { +// PageIfChanged counts calls and answers like the API, sending pages +// only when their checksum changed. +func (f *fakeSource) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) { + p, err := f.page(ctx, host, slug) + if err == nil && checksum != "" && p.Checksum() == checksum { + f.mu.Lock() + f.unchanged++ + f.mu.Unlock() + return agentapi.PageSnapshot{}, agentapi.ErrNotModified + } + return p, err +} + +func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) { f.mu.Lock() f.calls++ err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false @@ -508,3 +523,35 @@ func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) { t.Errorf("GET after the page left the list = %d, want 404", code) } } + +func TestRefreshSkipsUnchangedPages(t *testing.T) { + dir := t.TempDir() + now := time.Now() + src := newSource() + h := newHarness(t, src, dir, &now) + h.srv.Sync(context.Background()) + now = now.Add(syncInterval) + h.srv.Sync(context.Background()) + src.mu.Lock() + unchanged := src.unchanged + src.mu.Unlock() + if unchanged != 2 { + t.Errorf("unchanged answers on the second sync = %d, want 2", unchanged) + } + if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") { + t.Error("an unchanged page is not served as current") + } + + // A changed page is sent again, and the checksum survives a restart. + src.set(func(f *fakeSource) { + f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational} + }) + restarted := newHarness(t, src, dir, &now) + restarted.srv.Sync(context.Background()) + src.mu.Lock() + unchanged = src.unchanged + src.mu.Unlock() + if _, body := restarted.get("status.example.test", "/acme"); !strings.Contains(body, "Renamed") || unchanged != 3 { + t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged) + } +}