feat(agents): talk to the API over a WebSocket and push page changes
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m29s
ci / test (pull_request) Successful in 12m55s
ci / build (pull_request) Successful in 16m45s
ci / image (pull_request) Successful in 5m41s

Checkers and status page servers keep one WebSocket open to the API at
/agent/v1/stream and send their requests over it. The API answers them
through the agent API as if they had come over HTTP, each authenticated
again, so the protocol stays the same and a revoked token ends the
stream. While the stream is down agents fall back to plain HTTP, and an
API without it is asked again every five minutes.

Over the stream the API tells status page servers which of their pages
changed, so they fetch them at once instead of on their next refresh:
when a region of a monitor changes between up and down, an incident
opens or resolves, or anything of the organization is edited. Changes
are announced through Redis to every API instance and sent at most every
five seconds per stream. A page that changes while it is fetched is
fetched once more.

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-26 17:21:30 +01:00
1 parent 27338f0557
commit 538c43b563
21 files changed
+1091 -45

No files matched your search

+9 -3
View File
@@ -38,9 +38,10 @@ const (
)
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g := r.Group(agentapi.Prefix, s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/update", s.agentUpdate)
g.GET(agentapi.StreamPath, s.agentStream)
sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage)
sp.GET("/pages/index", s.agentPageIndex)
@@ -301,7 +302,10 @@ func (s *Server) agentResults(c *gin.Context) {
}
now := time.Now()
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
var accepted []agentapi.Result
var (
accepted []agentapi.Result
changed []uuid.UUID
)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
a := agentOf(c)
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
@@ -337,7 +341,8 @@ func (s *Server) agentResults(c *gin.Context) {
if len(params) == 0 {
return nil
}
return insertResults(ctx, q, params)
changed, err = insertResults(ctx, q, params)
return err
})
if err != nil {
// Unclaimed, the checker's retry is stored instead.
@@ -345,6 +350,7 @@ func (s *Server) agentResults(c *gin.Context) {
internalError(c, err)
return
}
s.pagesChanged(ctx, changed...)
s.evaluateResults(ctx, region, accepted, monitors)
s.storeEvidence(ctx, region, instance, accepted, monitors)
s.finishRunning(ctx, instance, accepted)
+3 -1
View File
@@ -50,7 +50,9 @@ func (s *Server) evaluateResults(ctx context.Context, region string, results []a
Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions,
})
if err == nil && t != evaluate.None {
err = s.transition(ctx, m, t, r.StartedAt)
if err = s.transition(ctx, m, t, r.StartedAt); err == nil {
s.pagesChanged(ctx, m.OrgID)
}
}
if err != nil {
// The next result re-evaluates; a missed transition only delays
+2
View File
@@ -54,6 +54,8 @@ func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) {
id := uuid.New()
client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client())
ctx, cancel := context.WithCancel(context.Background())
// Checkers talk to the API over the stream, as in production.
client.UseStream(ctx, agentapi.StreamOptions{})
done := make(chan struct{})
go func() {
defer close(done)
+5 -1
View File
@@ -92,12 +92,16 @@ func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.
if msg != "" {
row.Error = ptr(truncateValid(msg, 500))
}
var changed []uuid.UUID
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return insertResults(ctx, q, []store.InsertCheckResultsParams{row})
var err error
changed, err = insertResults(ctx, q, []store.InsertCheckResultsParams{row})
return err
})
if err != nil {
return err
}
s.pagesChanged(ctx, changed...)
s.evaluateResults(ctx, region,
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
map[uuid.UUID]store.MonitorsForResultsRow{id: {
+4 -1
View File
@@ -29,7 +29,10 @@ func TestLatestResultsKeepTheNewest(t *testing.T) {
r["monitor_id"], r["org_id"], r["region"] = id, org, region
}
b, _ := json.Marshal(rows)
if err := e.asSystem(t, func(tx pgx.Tx) error { return store.New(tx).UpsertLatestResults(context.Background(), b) }); err != nil {
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := store.New(tx).UpsertLatestResults(context.Background(), b)
return err
}); err != nil {
t.Fatal(err)
}
}
+35 -5
View File
@@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
"slices"
"time"
"github.com/google/uuid"
@@ -10,6 +11,12 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// regionKey identifies a monitor in one region.
type regionKey struct {
monitor uuid.UUID
region string
}
// latestRow is a result as UpsertLatestResults reads it.
type latestRow struct {
MonitorID uuid.UUID `json:"monitor_id"`
@@ -24,10 +31,11 @@ type latestRow struct {
// insertResults stores results and keeps the newest per monitor and
// region in latest_results, which the console reads instead of a day of
// results.
func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) error {
// results. It returns the organizations whose status changed somewhere,
// for pagesChanged once the transaction is committed.
func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) ([]uuid.UUID, error) {
if _, err := q.InsertCheckResults(ctx, rows); err != nil {
return err
return nil, err
}
latest := make([]latestRow, len(rows))
for i, r := range rows {
@@ -38,7 +46,29 @@ func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertChe
}
b, err := json.Marshal(latest)
if err != nil {
return err
return nil, err
}
return q.UpsertLatestResults(ctx, b)
ids := make([]uuid.UUID, len(rows))
for i, r := range rows {
ids[i] = r.MonitorID
}
before, err := q.LatestOK(ctx, ids)
if err != nil {
return nil, err
}
was := make(map[regionKey]bool, len(before))
for _, r := range before {
was[regionKey{r.MonitorID, r.Region}] = r.Ok
}
written, err := q.UpsertLatestResults(ctx, b)
if err != nil {
return nil, err
}
var changed []uuid.UUID
for _, w := range written {
if ok, seen := was[regionKey{w.MonitorID, w.Region}]; (!seen || ok != w.Ok) && !slices.Contains(changed, w.OrgID) {
changed = append(changed, w.OrgID)
}
}
return changed, nil
}
+7 -2
View File
@@ -58,6 +58,8 @@ type Server struct {
support *versioned[supportSettings]
// draining, once closed, ends the long polls of checkers.
draining <-chan struct{}
// handler serves the requests agents send over their streams.
handler http.Handler
// snapshots lets status page servers asking for the same page at once
// share one build of it.
snapshots singleflight.Group
@@ -107,6 +109,9 @@ func (s *Server) EndLongPollsOn(ch <-chan struct{}) { s.draining = ch }
// Mount installs session loading, locale resolution and CSRF protection and
// registers the JSON API and the console pages below them.
func (s *Server) Mount(r gin.IRouter) {
if h, ok := r.(http.Handler); ok {
s.handler = h
}
// Agents authenticate with tokens and never carry cookies, so they skip
// the session and CSRF middleware.
s.mountAgentAPI(r)
@@ -155,7 +160,7 @@ func (s *Server) Mount(r gin.IRouter) {
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
v1.POST("/invitations/:token/signup", s.inviteSignup)
org := v1.Group("/org", s.orgAccess())
org := v1.Group("/org", s.orgAccess(), s.announcePages())
org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy)
org.GET("/export", sessionOnly(), can(authz.OrgManage), s.exportOrg)
org.GET("/legal", can(authz.OrgManage), s.orgListLegal)
@@ -197,7 +202,7 @@ func (s *Server) Mount(r gin.IRouter) {
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
admin := v1.Group("/admin", s.requireAdmin())
admin := v1.Group("/admin", s.requireAdmin(), s.announcePages())
admin.GET("/audit", s.listPlatformAudit)
admin.GET("/check-types", s.adminListCheckTypes)
admin.PUT("/check-types", s.adminSetCheckTypes)
+357
View File
@@ -0,0 +1,357 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/url"
"path"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const (
// pagesChannel is the Redis channel announcing organizations whose
// status pages changed; uuid.Nil stands for all of them.
pagesChannel = "uptimesebi:pages-changed"
// streamInFlight bounds the requests of one stream handled at once.
streamInFlight = 128
// streamReadLimit bounds a request read from a stream.
streamReadLimit = 16 << 20
streamPing = 30 * time.Second
// pushFirst and pushEvery pace the page events of one stream: changes
// are collected for pushFirst, and a stream gets at most one event per
// pushEvery, so a flapping monitor does not have its pages rebuilt
// over and over.
pushFirst = time.Second
pushEvery = 5 * time.Second
// drainWait is how long a draining instance lets requests on a stream
// finish before closing it.
drainWait = 5 * time.Second
)
// streamedKey marks requests that arrived over a stream.
type streamedKey struct{}
// pagesChanged announces that status pages of orgs may look different
// now, so status page servers fetch them at once instead of on their next
// refresh. Losing the announcement only delays that.
func (s *Server) pagesChanged(ctx context.Context, orgs ...uuid.UUID) {
if s.rdb == nil {
return
}
for _, org := range orgs {
if err := s.rdb.Publish(ctx, pagesChannel, org.String()).Err(); err != nil {
s.log.WarnContext(ctx, "announcing changed status pages failed", "org", org, "error", err)
return
}
}
}
// announcePages is middleware announcing the changed status pages of the
// request's organization, or of all with no organization, after every
// change made through it.
func (s *Server) announcePages() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead || c.Writer.Status() >= 400 {
return
}
org := uuid.Nil
if p, ok := c.Get(ctxPrincipal); ok {
org = p.(*principal).Org.ID
}
s.pagesChanged(context.WithoutCancel(c.Request.Context()), org)
}
}
// agentStream serves an agent's stream: its requests run through the
// agent API as if they had come over HTTP, each authenticated again, and
// status page servers get told which of their pages changed.
func (s *Server) agentStream(c *gin.Context) {
up := c.Request
if up.Context().Value(streamedKey{}) != nil || s.handler == nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ws, err := websocket.Accept(c.Writer, up, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
if err != nil {
// Accept has answered the request.
return
}
ws.SetReadLimit(streamReadLimit)
a := agentOf(c)
ctx, cancel := context.WithCancel(context.WithoutCancel(up.Context()))
defer cancel()
st := &stream{s: s, ws: ws, up: up.Clone(ctx), ctx: ctx, inflight: map[uint64]context.CancelFunc{}}
go st.ping(cancel)
if a.Kind == "statuspage" {
go s.pushPages(ctx, st, a.OrgID)
}
if s.draining != nil {
go func() {
select {
case <-s.draining:
st.drain()
case <-ctx.Done():
}
}()
}
err = st.read()
cancel()
st.wg.Wait()
_ = ws.CloseNow()
s.log.DebugContext(ctx, "agent stream closed", "agent", a.ID, "error", err)
}
// stream is one open agent stream on the API's side.
type stream struct {
s *Server
ws *websocket.Conn
up *http.Request
ctx context.Context
mu sync.Mutex
inflight map[uint64]context.CancelFunc
draining bool
wg sync.WaitGroup
}
func (st *stream) read() error {
for {
_, msg, err := st.ws.Read(st.ctx)
if err != nil {
return err
}
f, body, err := agentapi.DecodeFrame(msg)
if err != nil {
continue
}
st.mu.Lock()
if f.Cancel {
if cancel := st.inflight[f.ID]; cancel != nil {
cancel()
}
st.mu.Unlock()
continue
}
_, dup := st.inflight[f.ID]
refuse := 0
switch {
case st.draining:
refuse = http.StatusServiceUnavailable
case dup || f.ID == 0:
refuse = http.StatusBadRequest
case len(st.inflight) >= streamInFlight:
refuse = http.StatusTooManyRequests
}
if refuse != 0 {
st.mu.Unlock()
st.reply(f.ID, refuse, nil, nil)
continue
}
rctx, cancel := context.WithCancel(context.WithValue(st.ctx, streamedKey{}, true))
st.inflight[f.ID] = cancel
st.wg.Add(1)
st.mu.Unlock()
go func() {
defer st.wg.Done()
defer func() {
st.mu.Lock()
delete(st.inflight, f.ID)
st.mu.Unlock()
cancel()
}()
st.serve(rctx, f, body)
}()
}
}
// serve runs one request through the agent API.
func (st *stream) serve(ctx context.Context, f agentapi.Frame, body []byte) {
u, err := url.Parse(agentapi.Prefix + f.Path)
switch {
case err != nil, path.Clean(u.Path) != u.Path, !strings.HasPrefix(u.Path, agentapi.Prefix+"/"),
u.Path == agentapi.Prefix+agentapi.StreamPath:
st.reply(f.ID, http.StatusBadRequest, nil, nil)
return
}
switch f.Method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch:
default:
st.reply(f.ID, http.StatusMethodNotAllowed, nil, nil)
return
}
req, err := http.NewRequestWithContext(ctx, f.Method, u.String(), bytes.NewReader(body))
if err != nil {
st.reply(f.ID, http.StatusBadRequest, nil, nil)
return
}
if f.Header != nil {
req.Header = f.Header
}
// Who is asking comes from the stream, never from the request.
for _, k := range []string{"Authorization", agentapi.VersionHeader, agentapi.InstanceHeader, agentapi.ReleaseHeader,
"X-Forwarded-For", "X-Real-Ip", "X-Forwarded-Proto", "X-Forwarded-Host"} {
req.Header.Del(k)
if v := st.up.Header.Values(k); len(v) > 0 {
req.Header[k] = v
}
}
req.Host, req.RemoteAddr, req.RequestURI = st.up.Host, st.up.RemoteAddr, u.RequestURI()
w := &replyWriter{header: http.Header{}}
st.s.handler.ServeHTTP(w, req)
if w.status == 0 {
w.status = http.StatusOK
}
st.reply(f.ID, w.status, w.header, w.body.Bytes())
if w.status == http.StatusUnauthorized {
// The token was revoked: the stream ends with it.
_ = st.ws.Close(websocket.StatusPolicyViolation, "unauthenticated")
}
}
func (st *stream) reply(id uint64, status int, h http.Header, body []byte) {
st.send(agentapi.Frame{ID: id, Status: status, Header: h}, body)
}
func (st *stream) send(f agentapi.Frame, body []byte) {
ctx, cancel := context.WithTimeout(st.ctx, time.Minute)
defer cancel()
if err := st.ws.Write(ctx, websocket.MessageBinary, agentapi.EncodeFrame(f, body)); err != nil {
_ = st.ws.CloseNow()
}
}
// ping closes streams whose agent stopped answering.
func (st *stream) ping(cancel context.CancelFunc) {
tick := time.NewTicker(streamPing)
defer tick.Stop()
for {
select {
case <-st.ctx.Done():
return
case <-tick.C:
ctx, stop := context.WithTimeout(st.ctx, streamPing/2)
err := st.ws.Ping(ctx)
stop()
if err != nil {
cancel()
_ = st.ws.CloseNow()
return
}
}
}
}
// drain refuses new requests, lets those running finish for a while and
// closes the stream, so the agent reconnects to another instance.
func (st *stream) drain() {
st.mu.Lock()
st.draining = true
st.mu.Unlock()
done := make(chan struct{})
go func() { st.wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(drainWait):
case <-st.ctx.Done():
}
_ = st.ws.Close(websocket.StatusGoingAway, "instance shutting down")
}
// pushPages tells a status page server which of its pages changed, for an
// organization's server only those of its organization.
func (s *Server) pushPages(ctx context.Context, st *stream, agentOrg *uuid.UUID) {
sub := s.rdb.Subscribe(ctx, pagesChannel)
defer func() { _ = sub.Close() }()
msgs := sub.Channel()
changed := map[uuid.UUID]bool{}
var (
due <-chan time.Time
last time.Time
)
for {
select {
case <-ctx.Done():
return
case m, ok := <-msgs:
if !ok {
return
}
org, err := uuid.Parse(m.Payload)
if err != nil || (agentOrg != nil && org != *agentOrg && org != uuid.Nil) {
continue
}
changed[org] = true
if due == nil {
due = time.After(max(pushFirst, pushEvery-time.Since(last)))
}
case <-due:
due, last = nil, time.Now()
refs, err := s.changedPages(ctx, agentOrg, changed)
clear(changed)
if err != nil {
s.log.WarnContext(ctx, "finding changed status pages failed", "error", err)
continue
}
if len(refs) == 0 {
continue
}
body, _ := json.Marshal(agentapi.PagesEvent{Pages: refs})
st.send(agentapi.Frame{Event: agentapi.EventPages}, body)
}
}
}
// changedPages lists the pages the server of agentOrg serves of the
// organizations changed.
func (s *Server) changedPages(ctx context.Context, agentOrg *uuid.UUID, changed map[uuid.UUID]bool) ([]agentapi.PageRef, error) {
var rows []store.ServablePagesRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ServablePages(ctx, agentOrg)
return err
})
var refs []agentapi.PageRef
for _, r := range rows {
if changed[uuid.Nil] || changed[r.OrgID] {
refs = append(refs, agentapi.PageRef{Slug: r.Slug, Host: r.Host})
}
}
return refs, err
}
// replyWriter collects a response to send back over a stream.
type replyWriter struct {
header http.Header
status int
body bytes.Buffer
}
// Header implements http.ResponseWriter.
func (w *replyWriter) Header() http.Header { return w.header }
// WriteHeader implements http.ResponseWriter.
func (w *replyWriter) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
}
// Write implements http.ResponseWriter.
func (w *replyWriter) Write(b []byte) (int, error) {
w.WriteHeader(http.StatusOK)
return w.body.Write(b)
}
+78
View File
@@ -0,0 +1,78 @@
package api_test
import (
"context"
"encoding/json"
"errors"
"slices"
"testing"
"time"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestAgentStream(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
owner := e.browser(t)
owner.signup("o@"+uniq("st")+".test", uniq("st-"))
slug := uniq("stream-")
_, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Before"})
pageID := body["id"].(string)
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Before", "published": true})
sp := e.statuspageClient(t, nil)
events := make(chan agentapi.PagesEvent, 16)
sp.UseStream(ctx, agentapi.StreamOptions{OnEvent: func(event string, body []byte) {
var ev agentapi.PagesEvent
if event == agentapi.EventPages && json.Unmarshal(body, &ev) == nil {
events <- ev
}
}})
waitFor(t, 10*time.Second, "stream to open", sp.Streaming)
snap, err := sp.Page(ctx, "", slug)
if err != nil || snap.Title != "Before" {
t.Fatalf("Page() over the stream = %q, %v", snap.Title, err)
}
if _, err := sp.PageIfChanged(ctx, "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) {
t.Errorf("PageIfChanged(current checksum) over the stream error = %v, want not modified", err)
}
if _, err := sp.Page(ctx, "", uniq("missing-")); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("Page(missing) over the stream error = %v, want not found", err)
}
// Editing the page tells the server at once.
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "After", "published": true})
deadline := time.After(10 * time.Second)
for told := false; !told; {
select {
case ev := <-events:
told = slices.ContainsFunc(ev.Pages, func(r agentapi.PageRef) bool { return r.Slug == slug })
case <-deadline:
t.Fatal("no event for the edited page")
}
}
if snap, err := sp.Page(ctx, "", slug); err != nil || snap.Title != "After" {
t.Errorf("Page() after the edit = %q, %v", snap.Title, err)
}
// A revoked token ends the stream.
hello, err := sp.Hello(ctx)
if err != nil {
t.Fatal(err)
}
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM agents WHERE id = $1`, hello.AgentID)
return err
}); err != nil {
t.Fatal(err)
}
if _, err := sp.Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
t.Errorf("Hello() with a revoked token error = %v, want unauthorized", err)
}
waitFor(t, 10*time.Second, "stream to close", func() bool { return !sp.Streaming() })
}