feat: status pages served by the right servers, cached before their first visit #151
No files matched your search
@@ -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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user