Merge pull request 'feat(agents): talk to the API over a WebSocket and push page changes' (#161) from feat/agent-websocket into main
ci / build (push) Successful in 20m33s
ci / lint (push) Successful in 12m10s
ci / test (push) Successful in 9m25s
ci / image (push) Successful in 5m55s
release / release (push) Successful in 38m55s

This commit was merged in pull request #161.
This commit is contained in:
Sebi committed 2026-11-26 16:48:08 +00:00
commit df39b765cb
21 files changed
+1091 -45

No files matched your search

+2
View File
@@ -102,6 +102,8 @@ docker run -d --restart unless-stopped -e UPTIME_API_URL=https://uptime.example.
git.zb-server.de/zb-server/uptimesebi-checker:latest
```
Agents keep one WebSocket open to the API (`/agent/v1/stream`) and send their requests over it. Over it the API also tells status page servers at once when a page changed, e.g. when a monitor fails or the page is edited. A proxy in front of the API must pass WebSocket upgrades. While the WebSocket is down, agents fall back to plain HTTPS requests, and pages are refreshed every 30 seconds as before.
The quickest way onto a Linux host with Docker is the install script your platform serves, with its address filled in. It checks the host, writes `/opt/uptimesebi/<kind>/compose.yaml` and `.env` (the token readable only by root) and starts the agent:
```sh
+1
View File
@@ -65,6 +65,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
log = log.With("region", hello.Region, "agent", hello.Name, "instance", instance)
log.Info("connected to api")
client.UseStream(ctx, agentapi.StreamOptions{Log: log})
runner := checker.New(client, cfg.Concurrency, log)
health := platform.NewHealth(map[string]platform.Probe{"api": runner.Healthy})
r := platform.NewRouter(log)
+2
View File
@@ -77,6 +77,8 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
if err != nil {
return err
}
// Pages are told about changes over the stream and fetched through it.
client.UseStream(ctx, agentapi.StreamOptions{Log: log, OnEvent: pages.OnEvent})
apiProbe := func(ctx context.Context) error { _, err := client.Hello(ctx); return err }
health := platform.NewHealth(map[string]platform.Probe{
"pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) },
+363
View File
@@ -0,0 +1,363 @@
package agentapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/coder/websocket"
)
// The stream is one WebSocket from an agent to the API. It carries the
// agent's requests, which the API answers as if they had come over HTTP,
// and events the API sends unasked, such as which status pages changed.
// Agents fall back to plain HTTP while it is down, and an API without it
// is asked again only now and then.
const (
// Prefix is the path of the agent API.
Prefix = "/agent/v1"
// StreamPath is where agents open the stream, below Prefix.
StreamPath = "/stream"
// MaxFrame bounds a frame read from the stream.
MaxFrame = 64 << 20
// EventPages lists pages that changed, as a PagesEvent.
EventPages = "pages"
)
// Frame is the header of a stream message. A message is the header as
// JSON, a newline and the body. Requests carry ID, Method and Path, replies
// the request's ID and Status, events Event; Cancel withdraws a request.
type Frame struct {
ID uint64 `json:"id,omitempty"`
Method string `json:"method,omitempty"`
// Path is below Prefix and includes the query.
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
Header http.Header `json:"header,omitempty"`
Cancel bool `json:"cancel,omitempty"`
Event string `json:"event,omitempty"`
}
// PagesEvent names status pages that changed and should be fetched again.
type PagesEvent struct {
Pages []PageRef `json:"pages"`
}
// EncodeFrame builds a stream message.
func EncodeFrame(f Frame, body []byte) []byte {
head, _ := json.Marshal(f)
out := make([]byte, 0, len(head)+1+len(body))
return append(append(append(out, head...), '\n'), body...)
}
// DecodeFrame splits a stream message into its header and body.
func DecodeFrame(msg []byte) (Frame, []byte, error) {
var f Frame
head, body, ok := bytes.Cut(msg, []byte{'\n'})
if !ok {
return f, nil, errors.New("agentapi: frame without header")
}
err := json.Unmarshal(head, &f)
return f, body, err
}
// StreamOptions configure UseStream.
type StreamOptions struct {
Log *slog.Logger
// OnEvent receives the events the API sends. It runs on the stream's
// reader and must not block.
OnEvent func(event string, body []byte)
}
const (
pingEvery = 20 * time.Second
pingTimeout = 15 * time.Second
// unsupportedRetry is how long an API without the stream is not asked
// again.
unsupportedRetry = 5 * time.Minute
)
var (
errStreamClosed = errors.New("agentapi: stream closed")
errStreamUnsupported = errors.New("agentapi: API has no stream")
)
// UseStream sends the client's requests over a WebSocket to the API from
// now on, while it is open, and keeps reopening it until ctx ends. Call it
// before the client is used concurrently.
func (c *Client) UseStream(ctx context.Context, o StreamOptions) {
if o.Log == nil {
o.Log = slog.New(slog.DiscardHandler)
}
fallback := c.hc.Transport
if fallback == nil {
fallback = http.DefaultTransport
}
// The handshake runs over the plain client; a client timeout would end
// the stream, so only the context bounds it.
dial := *c.hc
dial.Timeout = 0
t := &streamTransport{c: c, fallback: fallback, dial: &dial, opts: o}
hc := *c.hc
hc.Transport = t
c.hc = &hc
go t.run(ctx)
}
// Streaming reports whether requests currently go over the stream.
func (c *Client) Streaming() bool {
t, ok := c.hc.Transport.(*streamTransport)
return ok && t.current() != nil
}
// streamTransport sends requests over the stream while it is open and over
// fallback otherwise.
type streamTransport struct {
c *Client
fallback http.RoundTripper
dial *http.Client
opts StreamOptions
mu sync.Mutex
conn *streamConn
}
func (t *streamTransport) current() *streamConn {
t.mu.Lock()
defer t.mu.Unlock()
return t.conn
}
func (t *streamTransport) set(sc *streamConn) {
t.mu.Lock()
t.conn = sc
t.mu.Unlock()
}
// RoundTrip implements http.RoundTripper.
func (t *streamTransport) RoundTrip(req *http.Request) (*http.Response, error) {
sc := t.current()
path, below := strings.CutPrefix(req.URL.Path, Prefix)
if sc == nil || !below || path == StreamPath {
return t.fallback.RoundTrip(req)
}
var body []byte
if req.Body != nil {
var err error
body, err = io.ReadAll(req.Body)
_ = req.Body.Close()
if err != nil {
return nil, err
}
}
header := req.Header.Clone()
// The stream is authenticated once, as the agent that opened it.
for _, k := range []string{"Authorization", VersionHeader, InstanceHeader, ReleaseHeader} {
header.Del(k)
}
if req.URL.RawQuery != "" {
path += "?" + req.URL.RawQuery
}
f, rbody, sent, err := sc.roundTrip(req.Context(), Frame{Method: req.Method, Path: path, Header: header}, body)
if err != nil {
if !sent && req.Context().Err() == nil {
// Never reached the API: plain HTTP can still deliver it.
retry := req.Clone(req.Context())
retry.Body = io.NopCloser(bytes.NewReader(body))
return t.fallback.RoundTrip(retry)
}
return nil, err
}
if f.Header == nil {
f.Header = http.Header{}
}
return &http.Response{
Status: fmt.Sprintf("%d %s", f.Status, http.StatusText(f.Status)), StatusCode: f.Status,
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: f.Header,
Body: io.NopCloser(bytes.NewReader(rbody)), ContentLength: int64(len(rbody)), Request: req,
}, nil
}
// run keeps the stream open until ctx ends.
func (t *streamTransport) run(ctx context.Context) {
backoff := time.Second
var down time.Time
for ctx.Err() == nil {
sc, err := t.open(ctx)
if err != nil {
wait := backoff
if errors.Is(err, errStreamUnsupported) {
wait = unsupportedRetry
t.opts.Log.Info("the API has no WebSocket stream yet; using HTTP", "retry_in", wait.String())
} else {
t.opts.Log.Debug("opening the WebSocket to the API failed", "error", err, "retry_in", wait.String())
backoff = min(backoff*2, 30*time.Second)
}
sleepCtx(ctx, wait)
continue
}
backoff = time.Second
if down.IsZero() {
t.opts.Log.Info("connected to the API over WebSocket")
} else {
t.opts.Log.Info("connected to the API over WebSocket again", "down_for", time.Since(down).Round(time.Second).String())
}
t.set(sc)
err = sc.serve(ctx, t.opts.OnEvent)
t.set(nil)
down = time.Now()
if ctx.Err() == nil {
t.opts.Log.Info("WebSocket to the API closed; using HTTP until it is back", "error", err)
}
}
}
func (t *streamTransport) open(ctx context.Context) (*streamConn, error) {
u := t.c.base + Prefix + StreamPath
switch {
case strings.HasPrefix(u, "https://"):
u = "wss://" + strings.TrimPrefix(u, "https://")
case strings.HasPrefix(u, "http://"):
u = "ws://" + strings.TrimPrefix(u, "http://")
}
h := http.Header{}
h.Set("Authorization", "Bearer "+t.c.token)
h.Set(VersionHeader, fmt.Sprint(Version))
h.Set(InstanceHeader, t.c.instance.String())
h.Set(ReleaseHeader, t.c.release)
dctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
ws, resp, err := websocket.Dial(dctx, u, &websocket.DialOptions{
HTTPClient: t.dial, HTTPHeader: h, CompressionMode: websocket.CompressionContextTakeover,
})
if err != nil {
if resp != nil {
switch resp.StatusCode {
case http.StatusNotFound, http.StatusMethodNotAllowed:
return nil, errStreamUnsupported
case http.StatusUnauthorized:
return nil, ErrUnauthorized
}
}
return nil, err
}
ws.SetReadLimit(MaxFrame)
return &streamConn{ws: ws, waiting: map[uint64]chan reply{}, closed: make(chan struct{})}, nil
}
type reply struct {
f Frame
body []byte
}
// streamConn is one open stream.
type streamConn struct {
ws *websocket.Conn
mu sync.Mutex
next uint64
waiting map[uint64]chan reply
closed chan struct{}
}
// roundTrip sends a request and waits for its reply. sent reports whether
// the request may have reached the API.
func (sc *streamConn) roundTrip(ctx context.Context, f Frame, body []byte) (Frame, []byte, bool, error) {
ch := make(chan reply, 1)
sc.mu.Lock()
sc.next++
f.ID = sc.next
sc.waiting[f.ID] = ch
sc.mu.Unlock()
defer func() {
sc.mu.Lock()
delete(sc.waiting, f.ID)
sc.mu.Unlock()
}()
select {
case <-sc.closed:
return Frame{}, nil, false, errStreamClosed
default:
}
if err := sc.ws.Write(ctx, websocket.MessageBinary, EncodeFrame(f, body)); err != nil {
return Frame{}, nil, false, err
}
select {
case r := <-ch:
return r.f, r.body, true, nil
case <-sc.closed:
return Frame{}, nil, true, errStreamClosed
case <-ctx.Done():
// The API stops working on it, e.g. ends a long poll.
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
_ = sc.ws.Write(cctx, websocket.MessageBinary, EncodeFrame(Frame{ID: f.ID, Cancel: true}, nil))
cancel()
return Frame{}, nil, true, ctx.Err()
}
}
// serve reads replies and events until the stream closes or ctx ends.
func (sc *streamConn) serve(ctx context.Context, onEvent func(string, []byte)) error {
defer close(sc.closed)
done := make(chan struct{})
defer close(done)
go func() {
tick := time.NewTicker(pingEvery)
defer tick.Stop()
for {
select {
case <-done:
return
case <-ctx.Done():
_ = sc.ws.Close(websocket.StatusNormalClosure, "agent stopping")
return
case <-tick.C:
pctx, cancel := context.WithTimeout(ctx, pingTimeout)
err := sc.ws.Ping(pctx)
cancel()
if err != nil && ctx.Err() == nil {
_ = sc.ws.CloseNow()
return
}
}
}
}()
for {
_, msg, err := sc.ws.Read(context.WithoutCancel(ctx))
if err != nil {
_ = sc.ws.CloseNow()
return err
}
f, body, err := DecodeFrame(msg)
if err != nil {
continue
}
if f.Event != "" {
if onEvent != nil {
onEvent(f.Event, body)
}
continue
}
sc.mu.Lock()
ch := sc.waiting[f.ID]
sc.mu.Unlock()
if ch != nil {
ch <- reply{f: f, body: body}
}
}
}
func sleepCtx(ctx context.Context, d time.Duration) {
select {
case <-ctx.Done():
case <-time.After(d):
}
}
+47
View File
@@ -0,0 +1,47 @@
package agentapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
)
func TestFrameRoundTrip(t *testing.T) {
in := Frame{ID: 7, Method: http.MethodPut, Path: "/storage?key=a", Header: http.Header{"If-None-Match": {`"x"`}}}
f, body, err := DecodeFrame(EncodeFrame(in, []byte("line one\nline two")))
if err != nil || f.ID != 7 || f.Path != in.Path || f.Header.Get("If-None-Match") != `"x"` || string(body) != "line one\nline two" {
t.Errorf("DecodeFrame(EncodeFrame()) = %+v, %q, %v", f, body, err)
}
if _, _, err := DecodeFrame([]byte(`{"id":1}`)); err == nil {
t.Error("DecodeFrame(no newline) succeeded")
}
}
// An API without the stream is used over HTTP.
func TestStreamFallsBackToHTTP(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != Prefix+"/hello" {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(Hello{Name: "plain", Kind: "checker"})
}))
defer srv.Close()
c := NewClient(srv.URL, "usa_x", uuid.New(), "test")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c.UseStream(ctx, StreamOptions{})
time.Sleep(100 * time.Millisecond)
h, err := c.Hello(ctx)
if err != nil || h.Name != "plain" {
t.Fatalf("Hello() = %+v, %v", h, err)
}
if c.Streaming() {
t.Error("Streaming() = true against an API without the stream")
}
}
+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() })
}
+50 -8
View File
@@ -49,6 +49,8 @@ const (
// without asking the API again.
missFor = time.Minute
maxMissing = 10_000
// refreshTimeout bounds fetching one page.
refreshTimeout = 30 * time.Second
// unknownPerSecond bounds the lookups of hosts and slugs that are
// neither cached nor known to be missing, so a flood of made-up names
// is not passed on to the API. Every page the API lists is cached by
@@ -79,6 +81,9 @@ type Server struct {
mu sync.Mutex
cache map[string]entry
refreshing map[string]bool
// again holds pages that changed while being refreshed, which are
// fetched once more.
again map[string]bool
// visited holds when each cached page was last visited.
visited map[string]time.Time
// missing holds when a key was last found to have no page.
@@ -118,7 +123,7 @@ type Options struct {
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
s := &Server{
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, visited: map[string]time.Time{},
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, again: map[string]bool{}, visited: map[string]time.Time{},
missing: map[string]time.Time{},
}
for _, h := range o.Hosts {
@@ -419,7 +424,8 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
return e, true
}
// refresh fetches key unless another refresh of it is running.
// refresh fetches key unless another refresh of it is running, and once
// more if it changed meanwhile.
func (s *Server) refresh(ctx context.Context, key, host, slug string) {
s.mu.Lock()
if s.refreshing[key] {
@@ -428,14 +434,50 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
}
s.refreshing[key] = true
s.mu.Unlock()
defer func() {
for {
fctx, cancel := context.WithTimeout(ctx, refreshTimeout)
s.fetch(fctx, key, host, slug)
cancel()
s.mu.Lock()
delete(s.refreshing, key)
again := s.again[key] && ctx.Err() == nil
delete(s.again, key)
if !again {
delete(s.refreshing, key)
s.mu.Unlock()
return
}
s.mu.Unlock()
}()
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
s.fetch(ctx, key, host, slug)
}
}
// OnEvent handles the events the API sends over its stream: pages that
// changed are fetched at once instead of on their next refresh.
func (s *Server) OnEvent(event string, body []byte) {
if event != agentapi.EventPages {
return
}
var ev agentapi.PagesEvent
if err := json.Unmarshal(body, &ev); err != nil {
s.log.Warn("ignoring unreadable event", "event", event, "error", err)
return
}
for _, r := range ev.Pages {
s.changed("slug:"+r.Slug, "", r.Slug)
if r.Host != "" {
s.changed("host:"+r.Host, r.Host, "")
}
}
}
func (s *Server) changed(key, host, slug string) {
s.mu.Lock()
if s.refreshing[key] {
s.again[key] = true
s.mu.Unlock()
return
}
s.mu.Unlock()
s.background.Go(func() { s.refresh(context.Background(), key, host, slug) })
}
// Wait returns once the background refreshes started by visits are done.
+32
View File
@@ -555,3 +555,35 @@ func TestRefreshSkipsUnchangedPages(t *testing.T) {
t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged)
}
}
// Pages the API says changed are fetched at once, and once more when they
// change during that fetch.
func TestEventsRefreshPagesAtOnce(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, t.TempDir(), &now)
if code, body := h.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") {
t.Fatalf("first GET = %d", code)
}
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Acme renamed", Status: agentapi.PageOperational}
f.delay = 200 * time.Millisecond
f.calls = 0
})
event := []byte(`{"pages":[{"slug":"acme"}]}`)
h.srv.OnEvent(agentapi.EventPages, event)
time.Sleep(50 * time.Millisecond)
// Arrives while the first fetch runs.
h.srv.OnEvent(agentapi.EventPages, event)
h.srv.OnEvent("unknown", nil)
h.srv.Wait()
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme renamed") {
t.Error("page not refreshed after the event")
}
src.mu.Lock()
calls := src.calls
src.mu.Unlock()
if calls != 2 {
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
}
}
+69 -9
View File
@@ -12,6 +12,40 @@ import (
"github.com/google/uuid"
)
const latestOK = `-- name: LatestOK :many
SELECT monitor_id, region, ok FROM latest_results WHERE monitor_id = ANY ($1::uuid[])
`
type LatestOKRow struct {
MonitorID uuid.UUID
Region string
Ok bool
}
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Whether the newest result of each region of the monitors ids succeeded.
func (q *Queries) LatestOK(ctx context.Context, ids []uuid.UUID) ([]LatestOKRow, error) {
rows, err := q.db.Query(ctx, latestOK, ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestOKRow{}
for rows.Next() {
var i LatestOKRow
if err := rows.Scan(&i.MonitorID, &i.Region, &i.Ok); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestResults = `-- name: LatestResults :many
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
@@ -107,8 +141,7 @@ func (q *Queries) LatestResultsForMonitors(ctx context.Context, arg LatestResult
return items, nil
}
const upsertLatestResults = `-- name: UpsertLatestResults :exec
const upsertLatestResults = `-- name: UpsertLatestResults :many
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset($1::jsonb)
@@ -118,13 +151,40 @@ ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time
RETURNING monitor_id, region, org_id, ok
`
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
func (q *Queries) UpsertLatestResults(ctx context.Context, rows []byte) error {
_, err := q.db.Exec(ctx, upsertLatestResults, rows)
return err
type UpsertLatestResultsRow struct {
MonitorID uuid.UUID
Region string
OrgID uuid.UUID
Ok bool
}
// Keeps the newest of results, a JSON array, per monitor and
// region; results arriving late do not replace newer ones. It returns the
// rows it wrote.
func (q *Queries) UpsertLatestResults(ctx context.Context, results []byte) ([]UpsertLatestResultsRow, error) {
rows, err := q.db.Query(ctx, upsertLatestResults, results)
if err != nil {
return nil, err
}
defer rows.Close()
items := []UpsertLatestResultsRow{}
for rows.Next() {
var i UpsertLatestResultsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.OrgID,
&i.Ok,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+8 -5
View File
@@ -201,6 +201,10 @@ type Querier interface {
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Whether the newest result of each region of the monitors ids succeeded.
LatestOK(ctx context.Context, ids []uuid.UUID) ([]LatestOKRow, error)
LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error)
// Newest result per monitor and region in the org, of the last day.
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
@@ -426,11 +430,10 @@ type Querier interface {
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error)
UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
UpsertLatestResults(ctx context.Context, rows []byte) error
// Keeps the newest of results, a JSON array, per monitor and
// region; results arriving late do not replace newer ones. It returns the
// rows it wrote.
UpsertLatestResults(ctx context.Context, results []byte) ([]UpsertLatestResultsRow, error)
// A new version starts when the document is created or when the edit asks
// everyone to accept it again.
UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error
+11 -5
View File
@@ -1,18 +1,24 @@
-- latest_results holds the newest check result per monitor and region
-- (see migration 00055) and has row-level security.
-- name: UpsertLatestResults :exec
-- Keeps the newest of rows, a JSON array of results, per monitor and
-- region; results arriving late do not replace newer ones.
-- name: LatestOK :many
-- Whether the newest result of each region of the monitors ids succeeded.
SELECT monitor_id, region, ok FROM latest_results WHERE monitor_id = ANY (sqlc.arg(ids)::uuid[]);
-- name: UpsertLatestResults :many
-- Keeps the newest of results, a JSON array, per monitor and
-- region; results arriving late do not replace newer ones. It returns the
-- rows it wrote.
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset(sqlc.arg(rows)::jsonb)
FROM jsonb_to_recordset(sqlc.arg(results)::jsonb)
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
ORDER BY r.monitor_id, r.region, r.time DESC
ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time;
WHERE latest_results.time <= excluded.time
RETURNING monitor_id, region, org_id, ok;
-- name: LatestResults :many
-- Newest result per monitor and region in the org, of the last day.
+1 -1
View File
@@ -146,7 +146,7 @@ WHERE published AND suspended_at IS NULL
-- 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
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host, p.org_id
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
+5 -4
View File
@@ -470,7 +470,7 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar
}
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
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host, p.org_id
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
@@ -482,8 +482,9 @@ ORDER BY p.slug
`
type ServablePagesRow struct {
Slug string
Host string
Slug string
Host string
OrgID uuid.UUID
}
// System scope: the published pages a status page server serves, those
@@ -498,7 +499,7 @@ func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]Ser
items := []ServablePagesRow{}
for rows.Next() {
var i ServablePagesRow
if err := rows.Scan(&i.Slug, &i.Host); err != nil {
if err := rows.Scan(&i.Slug, &i.Host, &i.OrgID); err != nil {
return nil, err
}
items = append(items, i)