diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go index a60bdc4..821b70a 100644 --- a/internal/agentapi/agentapi.go +++ b/internal/agentapi/agentapi.go @@ -8,6 +8,7 @@ package agentapi import ( "bytes" + "compress/gzip" "context" "encoding/json" "errors" @@ -172,7 +173,18 @@ func (c *Client) doWith(ctx context.Context, method, path string, header http.He case out == nil: return nil } - return json.NewDecoder(resp.Body).Decode(out) + // Asked for explicitly, a compressed answer is not unpacked by the + // transport, nor ever over the stream. + var r io.Reader = resp.Body + if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") { + zr, err := gzip.NewReader(resp.Body) + if err != nil { + return fmt.Errorf("agentapi: %s %s: %w", method, path, err) + } + defer func() { _ = zr.Close() }() + r = zr + } + return json.NewDecoder(r).Decode(out) } // Hello identifies the agent and checks connectivity. diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go index 5930d56..6ce727f 100644 --- a/internal/agentapi/pages.go +++ b/internal/agentapi/pages.go @@ -407,9 +407,10 @@ func (c *Client) PageIfChanged(ctx context.Context, host, slug, checksum string) } else { q.Set("slug", slug) } - var h http.Header + // Pages run to megabytes of JSON that compresses many times over. + h := http.Header{"Accept-Encoding": {"gzip"}} if checksum != "" { - h = http.Header{"If-None-Match": {`"` + checksum + `"`}} + h.Set("If-None-Match", `"`+checksum+`"`) } var p PageSnapshot err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p) diff --git a/internal/api/statuspages.go b/internal/api/statuspages.go index 047f5dc..76205b9 100644 --- a/internal/api/statuspages.go +++ b/internal/api/statuspages.go @@ -1,6 +1,8 @@ package api import ( + "bytes" + "compress/gzip" "context" "crypto/rand" "encoding/hex" @@ -24,6 +26,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate" + "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" @@ -190,7 +193,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen comp := agentapi.Component{ ID: m.MonitorID.String(), Name: name, - Uptime: uptime90, + Uptime: roundRatio(uptime90), Days: dayHistory(days[m.MonitorID], now), } switch { @@ -308,7 +311,7 @@ func buildComponentDetails( ts := endHour.Add(-time.Duration(23-i) * time.Hour) hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1} if b, ok := byHour[ts.Unix()]; ok && b.Total > 0 { - hours[i].Uptime = float64(b.OK) / float64(b.Total) + hours[i].Uptime = roundRatio(float64(b.OK) / float64(b.Total)) hours[i].AvgLatencyMS = int(math.Round(float64(b.Latency))) } } @@ -330,10 +333,10 @@ func buildComponentDetails( } slices.SortFunc(regs, func(a, b agentapi.ComponentRegion) int { return strings.Compare(a.Name, b.Name) }) return &agentapi.ComponentDetails{ - SLA24h: web.Uptime(hourly), - SLA7d: web.Uptime(d7), - SLA30d: web.Uptime(d30), - SLA90d: uptime90, + SLA24h: roundRatio(web.Uptime(hourly)), + SLA7d: roundRatio(web.Uptime(d7)), + SLA30d: roundRatio(web.Uptime(d30)), + SLA90d: roundRatio(uptime90), Hours: hours, Regions: regs, } @@ -350,12 +353,24 @@ func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day { d := start.AddDate(0, 0, i).Format(time.DateOnly) out[i] = agentapi.Day{Date: d, Uptime: -1} if b, ok := byDay[d]; ok && b.Total > 0 { - out[i].Uptime = float64(b.OK) / float64(b.Total) + out[i].Uptime = roundRatio(float64(b.OK) / float64(b.Total)) } } return out } +// roundRatio rounds an uptime ratio to six decimals, finer than any page +// shows it. Unrounded, a ratio takes up to 18 characters, and a large page +// holds 90 of them for every component. A ratio below 1 stays below 1, so +// a page never shows 100% for a component that failed. +func roundRatio(r float64) float64 { + v := math.Round(r*1e6) / 1e6 + if v >= 1 && r < 1 { + return 0.999999 + } + return v +} + // agentPage serves a page snapshot to status page servers. Org-owned // servers only receive their own org's pages. func (s *Server) agentPage(c *gin.Context) { @@ -385,36 +400,71 @@ func (s *Server) agentPage(c *gin.Context) { } // 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.Header("ETag", snap.etag) + if c.GetHeader("If-None-Match") == snap.etag { c.Status(http.StatusNotModified) return } - c.JSON(http.StatusOK, snap) + // The encoded page is shared by everyone asking for it at once; large + // pages run to megabytes, encoding them per request ran the API out of + // memory. + body := snap.json + if platform.AcceptsGzip(c.GetHeader("Accept-Encoding")) { + c.Header("Content-Encoding", "gzip") + body = snap.gzip + } + c.Data(http.StatusOK, "application/json; charset=utf-8", body) +} + +// encodedSnapshot is a page snapshot as sent to status page servers. +type encodedSnapshot struct { + etag string + json []byte + gzip []byte +} + +// encodeSnapshot encodes snap once, as JSON and gzipped JSON. +func encodeSnapshot(snap agentapi.PageSnapshot) (encodedSnapshot, error) { + raw, err := json.Marshal(snap) + if err != nil { + return encodedSnapshot{}, err + } + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write(raw); err != nil { + return encodedSnapshot{}, err + } + if err := zw.Close(); err != nil { + return encodedSnapshot{}, err + } + return encodedSnapshot{etag: `"` + snap.Checksum() + `"`, json: raw, gzip: buf.Bytes()}, nil } // snapshotTimeout bounds a shared snapshot build, which outlives the // request that started it. const snapshotTimeout = time.Minute -// sharedSnapshot builds page once for all status page servers asking for it -// at the same time, as they do when told that it changed. A server giving -// up does not cancel the build for the others. -func (s *Server) sharedSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) { +// sharedSnapshot builds and encodes page once for all status page servers +// asking for it at the same time, as they do when told that it changed. A +// server giving up does not cancel the build for the others. +func (s *Server) sharedSnapshot(ctx context.Context, page store.StatusPage) (encodedSnapshot, error) { ch := s.snapshots.DoChan(page.ID.String(), func() (any, error) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), snapshotTimeout) defer cancel() - return s.buildSnapshot(ctx, page) + snap, err := s.buildSnapshot(ctx, page) + if err != nil { + return nil, err + } + return encodeSnapshot(snap) }) select { case <-ctx.Done(): - return agentapi.PageSnapshot{}, ctx.Err() + return encodedSnapshot{}, ctx.Err() case r := <-ch: if r.Err != nil { - return agentapi.PageSnapshot{}, r.Err + return encodedSnapshot{}, r.Err } - return r.Val.(agentapi.PageSnapshot), nil + return r.Val.(encodedSnapshot), nil } } diff --git a/internal/api/statuspages_internal_test.go b/internal/api/statuspages_internal_test.go new file mode 100644 index 0000000..1ae5331 --- /dev/null +++ b/internal/api/statuspages_internal_test.go @@ -0,0 +1,19 @@ +package api + +import "testing" + +func TestRoundRatio(t *testing.T) { + for _, c := range []struct{ in, want float64 }{ + {1, 1}, + {-1, -1}, + {0, 0}, + {0.99930555555556, 0.999306}, + {0.99, 0.99}, + // One failure in millions still is not 100%. + {0.9999997, 0.999999}, + } { + if got := roundRatio(c.in); got != c.want { + t.Errorf("roundRatio(%v) = %v, want %v", c.in, got, c.want) + } + } +} diff --git a/internal/api/statuspages_test.go b/internal/api/statuspages_test.go index aae8dab..2db6ae0 100644 --- a/internal/api/statuspages_test.go +++ b/internal/api/statuspages_test.go @@ -1,6 +1,7 @@ package api_test import ( + "compress/gzip" "context" "encoding/json" "errors" @@ -9,6 +10,7 @@ import ( "net/http" "net/http/httptest" "slices" + "strconv" "strings" "testing" "time" @@ -481,3 +483,75 @@ func TestStatusPageGroupsAndDetails(t *testing.T) { } } } + +// TestAgentPageEncoding fetches a page as a status page server would, with +// and without gzip, and through both the HTTP API and the client. +func TestAgentPageEncoding(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + owner := e.browser(t) + owner.signup("o@"+uniq("enc")+".test", uniq("enc-")) + slug := uniq("enc-") + _, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Encoded"}) + owner.do("PUT", "/api/v1/org/statuspages/"+body["id"].(string), map[string]any{"slug": slug, "title": "Encoded", "published": true}) + + tok, params := api.NewAgentToken(nil, "statuspage", "sp-"+uuid.NewString()[:6], nil) + if err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error { + _, err := q.CreateAgent(ctx, params) + return err + }); err != nil { + t.Fatal(err) + } + // No transparent decompression: the test sees what the API sends. + hc := &http.Client{Transport: &http.Transport{DisableCompression: true, TLSClientConfig: e.srv.Client().Transport.(*http.Transport).TLSClientConfig}} + get := func(header map[string]string) *http.Response { + t.Helper() + req, _ := http.NewRequest(http.MethodGet, e.srv.URL+"/agent/v1/pages?slug="+slug, nil) + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set(agentapi.VersionHeader, strconv.Itoa(agentapi.Version)) + req.Header.Set(agentapi.InstanceHeader, uuid.NewString()) + for k, v := range header { + req.Header.Set(k, v) + } + resp, err := hc.Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = resp.Body.Close() }) + return resp + } + + plain := get(nil) + raw, _ := io.ReadAll(plain.Body) + var snap agentapi.PageSnapshot + if plain.StatusCode != http.StatusOK || plain.Header.Get("Content-Encoding") != "" || json.Unmarshal(raw, &snap) != nil || snap.Title != "Encoded" { + t.Fatalf("plain page = %d %q %.200s", plain.StatusCode, plain.Header.Get("Content-Encoding"), raw) + } + etag := plain.Header.Get("ETag") + if etag != `"`+snap.Checksum()+`"` { + t.Errorf("ETag = %s, want the checksum %s", etag, snap.Checksum()) + } + + packed := get(map[string]string{"Accept-Encoding": "gzip"}) + if packed.Header.Get("Content-Encoding") != "gzip" || packed.Header.Get("ETag") != etag { + t.Fatalf("gzip page encoding %q, ETag %q; want gzip and %s", packed.Header.Get("Content-Encoding"), packed.Header.Get("ETag"), etag) + } + zr, err := gzip.NewReader(packed.Body) + if err != nil { + t.Fatal(err) + } + var unpacked agentapi.PageSnapshot + if err := json.NewDecoder(zr).Decode(&unpacked); err != nil || unpacked.Checksum() != snap.Checksum() { + t.Errorf("the gzipped page differs from the plain one: %v", err) + } + + if st := get(map[string]string{"If-None-Match": etag, "Accept-Encoding": "gzip"}).StatusCode; st != http.StatusNotModified { + t.Errorf("page with the current ETag = %d, want 304", st) + } + + // The client asks for gzip and unpacks it, over plain HTTP too. + client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) + if got, err := client.Page(ctx, "", slug); err != nil || got.Checksum() != snap.Checksum() { + t.Errorf("client Page() = %q, %v; want the same page", got.Title, err) + } +} diff --git a/internal/platform/compress.go b/internal/platform/compress.go index 3dca27f..4683a8c 100644 --- a/internal/platform/compress.go +++ b/internal/platform/compress.go @@ -38,6 +38,10 @@ func Compress() gin.HandlerFunc { } } +// AcceptsGzip reports whether an Accept-Encoding header allows gzip, for +// handlers that send content compressed ahead of time. +func AcceptsGzip(header string) bool { return acceptsGzip(header) } + // acceptsGzip reports whether an Accept-Encoding header allows gzip. func acceptsGzip(header string) bool { for _, part := range strings.Split(header, ",") {