Files
uptimesebi/internal/platform/compress.go
T
Sebastian UnterschützandClaude Opus 5.5 9424824416
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m55s
ci / test (pull_request) Successful in 13m30s
ci / build (pull_request) Successful in 19m20s
ci / image (pull_request) Successful in 5m37s
fix(statuspages): encode a page once for all servers, gzipped
Every status page server asking for a page got it encoded anew: the
snapshot was marshalled once for its checksum and again for the answer,
then copied into a stream frame. A page of several thousand components
is about 20 MB of JSON, so servers fetching it together, as they do when
told it changed, ran both API pods out of their 512 MiB.

The shared build now also encodes the page once, as JSON and gzipped,
and every server asking at the same time gets those bytes. Servers ask
for gzip and unpack it, over HTTP and the stream; older ones still get
plain JSON. A 20 MB page shrinks to about 1 MB. Uptime ratios in the
snapshot are rounded to six decimals instead of up to 18 characters,
never to 100% for a component that failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 21:58:14 +01:00

147 lines
3.8 KiB
Go

package platform
import (
"compress/gzip"
"io"
"mime"
"net/http"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
// compressMin is the smallest body worth compressing, for responses that
// state their length.
const compressMin = 1024
var gzipWriters = sync.Pool{New: func() any {
w, _ := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression)
return w
}}
// Compress gzips text responses (HTML, CSS, JavaScript, JSON, XML, SVG) for
// clients that accept it. Status pages list thousands of components in
// markup that repeats itself, so this shrinks them many times over.
func Compress() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Vary", "Accept-Encoding")
if c.Request.Method == http.MethodHead || !acceptsGzip(c.Request.Header.Get("Accept-Encoding")) {
c.Next()
return
}
w := &gzipWriter{ResponseWriter: c.Writer}
c.Writer = w
defer w.finish()
c.Next()
}
}
// 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, ",") {
name, params, _ := strings.Cut(part, ";")
name = strings.ToLower(strings.TrimSpace(name))
if name != "gzip" && name != "*" {
continue
}
for _, p := range strings.Split(params, ";") {
k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
if strings.EqualFold(k, "q") {
if q, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && q == 0 {
return false
}
}
}
return true
}
return false
}
func compressible(contentType string) bool {
mt, _, err := mime.ParseMediaType(contentType)
if err != nil {
return false
}
switch {
case strings.HasPrefix(mt, "text/"):
return true
case mt == "application/json", mt == "application/javascript", mt == "image/svg+xml",
mt == "application/xml", mt == "application/rss+xml", mt == "application/atom+xml":
return true
}
return strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml")
}
// gzipWriter decides at the first write whether to compress, when the
// handler has set the status and headers.
type gzipWriter struct {
gin.ResponseWriter
decided bool
gz *gzip.Writer
}
func (w *gzipWriter) decide() {
w.decided = true
h := w.Header()
switch status := w.Status(); {
case status < 200, status == http.StatusNoContent, status == http.StatusNotModified, status == http.StatusPartialContent:
return
}
if h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) {
return
}
if n, err := strconv.Atoi(h.Get("Content-Length")); err == nil && n < compressMin {
return
}
h.Set("Content-Encoding", "gzip")
h.Del("Content-Length")
if etag := h.Get("ETag"); etag != "" && !strings.HasPrefix(etag, "W/") {
h.Set("ETag", "W/"+etag)
}
w.gz = gzipWriters.Get().(*gzip.Writer)
w.gz.Reset(w.ResponseWriter)
}
// Write compresses b if decide chose to, which it does at the first write.
func (w *gzipWriter) Write(b []byte) (int, error) {
if !w.decided {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.decide()
}
if w.gz == nil {
return w.ResponseWriter.Write(b)
}
return w.gz.Write(b)
}
// WriteString writes s like Write, so strings are compressed as well.
func (w *gzipWriter) WriteString(s string) (int, error) {
return w.Write([]byte(s))
}
// Flush sends what is compressed so far, for responses that stream.
func (w *gzipWriter) Flush() {
if w.gz != nil {
_ = w.gz.Flush()
}
w.ResponseWriter.Flush()
}
func (w *gzipWriter) finish() {
if w.gz == nil {
return
}
_ = w.gz.Close()
w.gz.Reset(io.Discard)
gzipWriters.Put(w.gz)
w.gz = nil
}