Compare commits

...
4 Commits
Author SHA1 Message Date
Sebi f3d0a4c844 Merge pull request 'feat: status pages served by the right servers, cached before their first visit' (#151) from feat/own-statuspage-servers into main
ci / image (push) Successful in 3m53s
release / release (push) Successful in 11m16s
ci / build (push) Successful in 16m30s
ci / test (push) Successful in 12m0s
ci / lint (push) Successful in 10m11s
2026-11-24 22:08:02 +00:00
Sebastian UnterschützandClaude Opus 5.5 fcf615dce7 feat(statuspage): refresh pages by checksum
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m46s
ci / test (push) Skipped
ci / image (pull_request) Successful in 3m24s
ci / test (pull_request) Successful in 14m46s
ci / build (pull_request) Successful in 18m49s
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
2026-11-24 22:57:22 +01:00
Sebastian UnterschützandClaude Opus 5.5 4e9a198b2f feat(statuspage): fetch every served page every five minutes
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Canceled after 5m23s
ci / lint (pull_request) Canceled after 5m23s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:51:46 +01:00
Sebastian UnterschützandClaude Opus 5.5 c0239e15bb feat(api): organizations with own status page servers serve their pages alone
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / lint (pull_request) Canceled after 6m3s
ci / test (pull_request) Canceled after 6m2s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
ci / image (push) Skipped
The platform's status page servers handed out every published page,
including those of organizations running their own servers. Once one of
an organization's own status page servers has connected, the agent API
now answers the platform's servers 404 for its pages, so they drop them
from their cache, and only the organization's servers serve them. A
created but never connected token changes nothing, so moving over does
not take the pages offline.

The console no longer links such pages to the platform's address,
which would not serve them; the editor says who does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:45:37 +01:00
18 changed files with 1239 additions and 798 deletions

No files matched your search

+1 -1
View File
@@ -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 | | Hybrid | hosted | at the customer | at the customer |
| Self-hosted | at the customer | 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. 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 ## Usage
+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))
+42 -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"
@@ -348,19 +351,57 @@ func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) {
return LegalDoc{}, false 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. // 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
} }
+1
View File
@@ -41,6 +41,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
g.GET("/update", s.agentUpdate) g.GET("/update", s.agentUpdate)
sp := g.Group("", requireAgentKind("statuspage")) sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage) sp.GET("/pages", s.agentPage)
sp.GET("/pages/index", s.agentPageIndex)
sp.GET("/storage", s.storageGet) sp.GET("/storage", s.storageGet)
sp.PUT("/storage", s.storagePut) sp.PUT("/storage", s.storagePut)
sp.DELETE("/storage", s.storageDelete) sp.DELETE("/storage", s.storageDelete)
+22 -6
View File
@@ -1016,19 +1016,31 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
return web.ChannelsPage(page, me, v), nil return web.ChannelsPage(page, me, v), nil
} }
func (s *Server) pageURL(p store.StatusPage) string { // pageURL is where p is reachable, or empty when only the organization's
// own status page servers serve it, at an address the platform does not
// know.
func (s *Server) pageURL(p store.StatusPage, ownServers bool) string {
if p.CustomDomain != nil && p.DomainVerifiedAt != nil { if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
return "https://" + *p.CustomDomain + "/" return "https://" + *p.CustomDomain + "/"
} }
if ownServers {
return ""
}
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
} }
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context() ctx := c.Request.Context()
var rows []store.StatusPage var (
rows []store.StatusPage
own bool
)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error var err error
rows, err = q.ListStatusPages(ctx) if rows, err = q.ListStatusPages(ctx); err != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
return err return err
}) })
if err != nil { if err != nil {
@@ -1041,7 +1053,7 @@ func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me
} }
v.Pages = append(v.Pages, web.PageRow{ v.Pages = append(v.Pages, web.PageRow{
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published, ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
URL: s.pageURL(r), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil, URL: s.pageURL(r, own), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
}) })
} }
return web.StatusPagesPage(page, me, v), nil return web.StatusPagesPage(page, me, v), nil
@@ -1059,6 +1071,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
pageGroups []store.StatusPageGroup pageGroups []store.StatusPageGroup
orgGroups []store.MonitorGroup orgGroups []store.MonitorGroup
monitors []store.Monitor monitors []store.Monitor
own bool
) )
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error var err error
@@ -1074,7 +1087,10 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if orgGroups, err = q.ListGroups(ctx); err != nil { if orgGroups, err = q.ListGroups(ctx); err != nil {
return err return err
} }
monitors, err = q.ListMonitors(ctx) if monitors, err = q.ListMonitors(ctx); err != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
return err return err
}) })
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -1089,7 +1105,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
Published: row.Published, ShowDetails: row.ShowComponentDetails, Published: row.Published, ShowDetails: row.ShowComponentDetails,
Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason, Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason,
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified, URL: s.pageURL(row, own), OwnServers: own, Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
HasOrgGroups: len(orgGroups) > 0, HasOrgGroups: len(orgGroups) > 0,
} }
if v.DomainRecord != nil { if v.DomainRecord != nil {
+40 -4
View File
@@ -346,14 +346,22 @@ func (s *Server) agentPage(c *gin.Context) {
fail(c, http.StatusBadRequest, "invalid_input") fail(c, http.StatusBadRequest, "invalid_input")
return return
} }
var page store.StatusPage var (
page store.StatusPage
own bool
)
a := agentOf(c)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error var err error
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}) if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
return err return err
}) })
a := agentOf(c) // The platform's servers leave the pages of organizations that serve
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) { // them on their own servers to those.
if errors.Is(err, pgx.ErrNoRows) || (err == nil && (own || a.OrgID != nil && *a.OrgID != page.OrgID)) {
fail(c, http.StatusNotFound, "not_found") fail(c, http.StatusNotFound, "not_found")
return return
} }
@@ -366,9 +374,37 @@ 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)
} }
// 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 { type statusPageRequest struct {
Slug string `json:"slug" binding:"required,max=63"` Slug string `json:"slug" binding:"required,max=63"`
Title string `json:"title" binding:"required,max=200"` Title string `json:"title" binding:"required,max=200"`
+38
View File
@@ -8,6 +8,7 @@ import (
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"slices"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -95,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) {
@@ -192,6 +199,37 @@ func TestStatusPages(t *testing.T) {
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"}) st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found") expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
}) })
t.Run("own servers replace the platform's", func(t *testing.T) {
org := uuid.MustParse(owner.orgID())
own := e.statuspageClient(t, &org)
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 {
t.Fatal(err)
}
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("platform server still gets the page: %v", err)
}
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")
}
})
} }
func editorEmail(b *browser) string { func editorEmail(b *browser) string {
+2
View File
@@ -1256,6 +1256,8 @@
"pages.logo": "Logo-URL (https)", "pages.logo": "Logo-URL (https)",
"pages.no_group": "Ohne Gruppe", "pages.no_group": "Ohne Gruppe",
"pages.open": "Öffnen", "pages.open": "Öffnen",
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
"pages.own_servers_short": "eigene Server",
"pages.page_title": "Titel", "pages.page_title": "Titel",
"pages.published": "Veröffentlicht", "pages.published": "Veröffentlicht",
"pages.section": "Abschnitt", "pages.section": "Abschnitt",
+2
View File
@@ -1256,6 +1256,8 @@
"pages.logo": "Logo URL (https)", "pages.logo": "Logo URL (https)",
"pages.no_group": "No group", "pages.no_group": "No group",
"pages.open": "Open", "pages.open": "Open",
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
"pages.own_servers_short": "own servers",
"pages.page_title": "Title", "pages.page_title": "Title",
"pages.published": "Published", "pages.published": "Published",
"pages.section": "Section", "pages.section": "Section",
+82 -15
View File
@@ -35,14 +35,24 @@ import (
const ( const (
// freshFor is how long a snapshot is used without asking the API. // freshFor is how long a snapshot is used without asking the API.
freshFor = 30 * time.Second freshFor = 30 * time.Second
// staleNoticeAfter is when visitors are told the state may be outdated. // refreshInterval is how often pages visited within recentFor are
staleNoticeAfter = 5 * time.Minute // refreshed.
refreshInterval = 30 * time.Second 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. // 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)
} }
// Server renders pages for one status page agent. // Server renders pages for one status page agent.
@@ -60,6 +70,8 @@ type Server struct {
mu sync.Mutex mu sync.Mutex
cache map[string]entry cache map[string]entry
refreshing map[string]bool refreshing map[string]bool
// visited holds when each page was last visited.
visited map[string]time.Time
// background tracks refreshes started by visits. // background tracks refreshes started by visits.
background sync.WaitGroup background sync.WaitGroup
} }
@@ -71,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.
@@ -88,7 +103,7 @@ type Options struct {
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) { func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
s := &Server{ s := &Server{
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir, 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 { for _, h := range o.Hosts {
s.ownHosts[strings.ToLower(h)] = true s.ownHosts[strings.ToLower(h)] = true
@@ -308,6 +323,7 @@ func (s *Server) localizeRequest(c *gin.Context) {
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) { func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
s.mu.Lock() s.mu.Lock()
e, cached := s.cache[key] e, cached := s.cache[key]
s.visited[key] = s.now()
s.mu.Unlock() s.mu.Unlock()
if cached { if cached {
if s.now().Sub(e.Fetched) >= freshFor { if s.now().Sub(e.Fetched) >= freshFor {
@@ -319,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
@@ -331,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()
@@ -361,25 +389,64 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
// Wait returns once the background refreshes started by visits are done. // Wait returns once the background refreshes started by visits are done.
func (s *Server) Wait() { s.background.Wait() } func (s *Server) Wait() { s.background.Wait() }
// Run keeps every known page fresh until ctx ends, so pages stay current // Run keeps pages fresh until ctx ends: every page the API lists every
// even without visitors and the cache is warm when the API goes away. // 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) { func (s *Server) Run(ctx context.Context) {
tick := time.NewTicker(refreshInterval) refresh := time.NewTicker(refreshInterval)
defer tick.Stop() defer refresh.Stop()
listAll := time.NewTicker(syncInterval)
defer listAll.Stop()
s.Sync(ctx)
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
case <-tick.C: case <-listAll.C:
s.Sync(ctx)
case <-refresh.C:
s.mu.Lock() s.mu.Lock()
entries := make([]entry, 0, len(s.cache)) var recent []entry
for _, e := range s.cache { for key, e := range s.cache {
entries = append(entries, e) if s.now().Sub(s.visited[key]) < recentFor {
recent = append(recent, e)
}
} }
s.mu.Unlock() s.mu.Unlock()
for _, e := range entries { for _, e := range recent {
s.refresh(ctx, e.Key, e.Host, e.Slug) 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)
}
}
+92 -1
View File
@@ -20,12 +20,27 @@ import (
type fakeSource struct { type fakeSource struct {
mu sync.Mutex mu sync.Mutex
calls int calls int
// unchanged counts the answers that the page had not changed.
unchanged int
err error err error
delay time.Duration delay time.Duration
pages map[string]agentapi.PageSnapshot 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
@@ -49,6 +64,21 @@ func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.Page
return p, nil 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)) { func (f *fakeSource) set(fn func(*fakeSource)) {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
@@ -464,3 +494,64 @@ 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)
}
}
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)
}
}
+16
View File
@@ -318,6 +318,22 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
return items, nil return items, nil
} }
const orgServesOwnPages = `-- name: OrgServesOwnPages :one
SELECT EXISTS (
SELECT 1 FROM agents
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
)
`
// An organization serves its status pages itself once one of its own
// status page servers has connected.
func (q *Queries) OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error) {
row := q.db.QueryRow(ctx, orgServesOwnPages, orgID)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows
UPDATE agents SET allow_private = $1 UPDATE agents SET allow_private = $1
WHERE id = $2 AND kind = 'checker' AND org_id = $3 WHERE id = $2 AND kind = 'checker' AND org_id = $3
+7
View File
@@ -289,6 +289,9 @@ type Querier interface {
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error) OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error) OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error) OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
// An organization serves its status pages itself once one of its own
// status page servers has connected.
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
// Organizations user owns, with their member and owner counts. // Organizations user owns, with their member and owner counts.
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
// The public updates of incidents shown on a status page, newest first. // The public updates of incidents shown on a status page, newest first.
@@ -334,6 +337,10 @@ type Querier interface {
// page from a keyset cursor whose string key is monitor and region. // page from a keyset cursor whose string key is monitor and region.
ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error) ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error)
ScrubAuditEmail(ctx context.Context, email string) 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) SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error)
SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error) SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error)
SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error
+8
View File
@@ -54,3 +54,11 @@ WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 s
-- name: SetAgentAllowPrivate :execrows -- name: SetAgentAllowPrivate :execrows
UPDATE agents SET allow_private = sqlc.arg(allow_private) UPDATE agents SET allow_private = sqlc.arg(allow_private)
WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id); WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id);
-- name: OrgServesOwnPages :one
-- An organization serves its status pages itself once one of its own
-- status page servers has connected.
SELECT EXISTS (
SELECT 1 FROM agents
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
);
+14
View File
@@ -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 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) 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))); 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;
+40
View File
@@ -352,6 +352,46 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar
return err 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 const setStatusPageDomain = `-- name: SetStatusPageDomain :one
UPDATE status_pages SET UPDATE status_pages SET
custom_domain = $1, custom_domain = $1,
+9 -1
View File
@@ -44,6 +44,8 @@ templ StatusPagesPage(p Page, me Me, v PagesView) {
} }
if pg.Suspended { if pg.Suspended {
<span class="ml-auto text-xs text-down">{ i18n.T(ctx, "pages.suspended") }</span> <span class="ml-auto text-xs text-down">{ i18n.T(ctx, "pages.suspended") }</span>
} else if pg.Published && pg.URL == "" {
<span class="ml-auto text-xs text-muted">{ i18n.T(ctx, "pages.own_servers_short") }</span>
} else if pg.Published { } else if pg.Published {
<a href={ templ.SafeURL(pg.URL) } class="ml-auto text-muted hover:text-ink" target="_blank" rel="noopener">{ i18n.T(ctx, "pages.open") } ↗</a> <a href={ templ.SafeURL(pg.URL) } class="ml-auto text-muted hover:text-ink" target="_blank" rel="noopener">{ i18n.T(ctx, "pages.open") } ↗</a>
} else { } else {
@@ -89,6 +91,9 @@ type PageMonitorOption struct {
// PageEditor is the data of the status page editor. // PageEditor is the data of the status page editor.
type PageEditor struct { type PageEditor struct {
// OwnServers is set when the organization's own status page servers
// serve its pages instead of the platform's.
OwnServers bool
ID string ID string
Title string Title string
Slug string Slug string
@@ -124,12 +129,15 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
<div class="mb-8 flex flex-wrap items-baseline justify-between gap-4"> <div class="mb-8 flex flex-wrap items-baseline justify-between gap-4">
<h1 class="text-lg font-semibold">{ e.Title }</h1> <h1 class="text-lg font-semibold">{ e.Title }</h1>
<span class="flex gap-5 text-sm"> <span class="flex gap-5 text-sm">
if e.Published { if e.Published && e.URL != "" {
<a href={ templ.SafeURL(e.URL) } target="_blank" rel="noopener" class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.open") } ↗</a> <a href={ templ.SafeURL(e.URL) } target="_blank" rel="noopener" class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.open") } ↗</a>
} }
<a href={ templ.SafeURL("/api/v1/org/statuspages/" + e.ID + "/export") } class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.export") }</a> <a href={ templ.SafeURL("/api/v1/org/statuspages/" + e.ID + "/export") } class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.export") }</a>
</span> </span>
</div> </div>
if e.OwnServers {
<p class="mb-6 border-l-2 border-ink pl-3 text-sm">{ i18n.T(ctx, "pages.own_servers") }</p>
}
<div class="grid gap-12 md:grid-cols-2"> <div class="grid gap-12 md:grid-cols-2">
<section> <section>
@sectionHeading("pages.settings") @sectionHeading("pages.settings")
File diff suppressed because it is too large. Load diff