feat(statuspage): refresh pages by checksum
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m46s
ci / test (pull_request) Successful in 14m46s
ci / build (pull_request) Successful in 18m49s
ci / image (pull_request) Successful in 3m24s

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 <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-24 22:57:22 +01:00
1 parent 4e9a198b2f
commit fcf615dce7
6 files changed
+120 -8

No files matched your search

+10
View File
@@ -125,6 +125,11 @@ func (c *Client) WithHTTPClient(hc *http.Client) *Client {
func (c *Client) Instance() uuid.UUID { return c.instance } func (c *Client) Instance() uuid.UUID { return c.instance }
func (c *Client) do(ctx context.Context, method, path string, in, out any) error { 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 var body io.Reader
if in != nil { if in != nil {
b, err := json.Marshal(in) 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(VersionHeader, fmt.Sprint(Version))
req.Header.Set(InstanceHeader, c.instance.String()) req.Header.Set(InstanceHeader, c.instance.String())
req.Header.Set(ReleaseHeader, c.release) req.Header.Set(ReleaseHeader, c.release)
for k, v := range header {
req.Header[k] = v
}
resp, err := c.hc.Do(req) resp, err := c.hc.Do(req)
if err != nil { if err != nil {
return err return err
@@ -152,6 +160,8 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
return ErrUnauthorized return ErrUnauthorized
case resp.StatusCode == http.StatusNotFound: case resp.StatusCode == http.StatusNotFound:
return ErrNotFound return ErrNotFound
case resp.StatusCode == http.StatusNotModified:
return ErrNotModified
case resp.StatusCode >= 300: case resp.StatusCode >= 300:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg)) return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
+25 -1
View File
@@ -2,6 +2,9 @@ package agentapi
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors" "errors"
"net/http" "net/http"
"net/url" "net/url"
@@ -368,16 +371,37 @@ func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
// ErrNotFound means no published page matches. // ErrNotFound means no published page matches.
var ErrNotFound = errors.New("agentapi: not found") 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 // Page fetches the published page for a custom domain host, or for slug if
// host is empty. // host is empty.
func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) { 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{} q := url.Values{}
if host != "" { if host != "" {
q.Set("host", host) q.Set("host", host)
} else { } else {
q.Set("slug", slug) q.Set("slug", slug)
} }
var h http.Header
if checksum != "" {
h = http.Header{"If-None-Match": {`"` + checksum + `"`}}
}
var p PageSnapshot 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 return p, err
} }
+8
View File
@@ -374,6 +374,14 @@ func (s *Server) agentPage(c *gin.Context) {
internalError(c, err) internalError(c, err)
return 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) c.JSON(http.StatusOK, snap)
} }
+6
View File
@@ -96,6 +96,12 @@ func TestStatusPages(t *testing.T) {
snap.Sections[1].Components[0].Name != "Public API" { snap.Sections[1].Components[0].Name != "Public API" {
t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap) 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) raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status"} { for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
if strings.Contains(string(raw), secret) { if strings.Contains(string(raw), secret) {
+20 -3
View File
@@ -49,7 +49,9 @@ const (
// Source fetches snapshots; *agentapi.Client implements it. // Source fetches snapshots; *agentapi.Client implements it.
type Source interface { 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) Pages(ctx context.Context) ([]agentapi.PageRef, error)
} }
@@ -81,6 +83,9 @@ type entry struct {
Slug string `json:"slug,omitempty"` Slug string `json:"slug,omitempty"`
Snap agentapi.PageSnapshot `json:"snapshot"` Snap agentapi.PageSnapshot `json:"snapshot"`
Fetched time.Time `json:"fetched"` 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. // 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) { 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 { 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): case errors.Is(err, agentapi.ErrNotFound):
s.forget(key) s.forget(key)
return entry{}, false return entry{}, false
@@ -342,7 +359,7 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
s.mu.Unlock() s.mu.Unlock()
return e, ok 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.mu.Lock()
s.cache[key] = e s.cache[key] = e
s.mu.Unlock() s.mu.Unlock()
+51 -4
View File
@@ -20,12 +20,27 @@ import (
type fakeSource struct { type fakeSource struct {
mu sync.Mutex mu sync.Mutex
calls int calls int
err error // unchanged counts the answers that the page had not changed.
delay time.Duration unchanged int
pages map[string]agentapi.PageSnapshot 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.mu.Lock()
f.calls++ f.calls++
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false 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) 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)
}
}