Compare commits

...
Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 d224ddcee2 ci: build the image with BuildKit (docker-cli-buildx)
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 7m34s
ci / build (pull_request) Successful in 16m13s
ci / image (pull_request) Successful in 28s
ci / test (push) Skipped
ci / test (pull_request) Successful in 8m45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:09:51 +01:00
Sebastian UnterschützandClaude Opus 5.5 b5864632bb ci: caches, prebuilt linters, image from the built binaries
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 4m38s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
ci / test (pull_request) Canceled after 5m37s
- Go module/build cache, golangci-lint cache and npm cache in the runners'
  S3 cache for lint, test and build; only main saves (one entry per
  commit), PRs and tags restore; release restores the build cache
- golangci-lint from the release tarball (sha256-checked) instead of
  compiling it with go install on every run
- shellcheck from its static release binary instead of apt-get on every run
- the image job packs the build job's amd64 binaries (Dockerfile.ci,
  distroless, same entrypoint) with the runner's Docker daemon instead of
  Kaniko rebuilding frontend and Go from the git context; Dockerfile stays
  for local/make builds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 15:04:32 +01:00
Sebi efd2f2d793 Merge pull request 'fix(statuspages): encode a page once for all servers, gzipped' (#178) from fix/page-snapshot-memory into main
ci / build (push) Successful in 17m41s
ci / test (push) Successful in 16m5s
ci / lint (push) Successful in 6m29s
release / release (push) Successful in 37m32s
ci / image (push) Successful in 3m38s
2026-11-29 21:00:25 +00:00
Sebastian UnterschützandClaude Opus 5.5 9424824416 fix(statuspages): encode a page once for all servers, gzipped
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
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
9 changed files with 320 additions and 66 deletions

No files matched your search

+117 -43
View File
@@ -13,7 +13,10 @@ concurrency:
env:
GOLANGCI_LINT_VERSION: v2.15.0
SQLC_VERSION: v1.31.1
# sha256 of golangci-lint-<version>-linux-amd64.tar.gz from the release's checksums.txt
GOLANGCI_LINT_SHA256: 9b7fe6a6bf6334b98decf8d86b11415ea7889afdabdd1959fdce23af2a9ebcea
HELM_VERSION: v3.19.0
SHELLCHECK_VERSION: v0.12.0
jobs:
lint:
@@ -29,8 +32,24 @@ jobs:
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz
echo /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/go/bin" >> "$GITHUB_PATH"
echo "GO_VERSION=$v" >> "$GITHUB_ENV"
# Module, build and npm caches live in the runners' S3 cache. Only main
# saves them (one entry per commit, expired by the bucket after 7 days);
# pull requests and tags restore the newest one from main.
- name: Restore caches
uses: actions/cache/restore@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.cache/golangci-lint
~/.npm
key: lint-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
restore-keys: |
lint-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-
lint-go${{ env.GO_VERSION }}-
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
run: npm ci --no-audit --no-fund --prefer-offline && npm run build
- name: Generated code is up to date
run: |
go tool templ generate
@@ -42,10 +61,15 @@ jobs:
run: test -z "$(gofmt -l internal cmd tools deploy)" || { gofmt -l internal cmd tools deploy; exit 1; }
- name: go vet
run: go vet ./...
# The release binary instead of `go install`, which compiled the linter
# from source on every run.
- name: golangci-lint
run: |
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION}
"$(go env GOPATH)/bin/golangci-lint" run ./...
v="${GOLANGCI_LINT_VERSION#v}"
curl -fsSLo /tmp/golangci-lint.tar.gz "https://github.com/golangci/golangci-lint/releases/download/${GOLANGCI_LINT_VERSION}/golangci-lint-${v}-linux-amd64.tar.gz"
echo "${GOLANGCI_LINT_SHA256} /tmp/golangci-lint.tar.gz" | sha256sum -c -
tar -xzf /tmp/golangci-lint.tar.gz -C /usr/local/bin --strip-components=1 "golangci-lint-${v}-linux-amd64/golangci-lint"
golangci-lint run ./...
- name: Helm chart
run: |
curl -fsSL "https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz" | tar -xz -C /usr/local/bin --strip-components=1 linux-amd64/helm
@@ -65,8 +89,20 @@ jobs:
# Debian and Raspberry Pi OS; the test renders and checks it.
- name: shellcheck
run: |
command -v shellcheck >/dev/null || { apt-get update -qq && apt-get install -y -qq shellcheck; }
# Static release binary instead of apt-get update + install on every run.
curl -fsSL "https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" \
| tar -xJ -C /usr/local/bin --strip-components=1 "shellcheck-${SHELLCHECK_VERSION}/shellcheck"
go test -count=1 -run 'TestScript|TestInstall' -v ./deploy/agent/ | grep -v '^=== RUN'
- name: Save caches
if: github.ref == 'refs/heads/main'
uses: actions/cache/save@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.cache/golangci-lint
~/.npm
key: lint-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
test:
runs-on: ubuntu-latest
@@ -126,8 +162,20 @@ jobs:
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz
echo /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/go/bin" >> "$GITHUB_PATH"
echo "GO_VERSION=$v" >> "$GITHUB_ENV"
- name: Restore caches
uses: actions/cache/restore@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.npm
key: test-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
restore-keys: |
test-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-
test-go${{ env.GO_VERSION }}-
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
run: npm ci --no-audit --no-fund --prefer-offline && npm run build
- name: Prepare database
# The same roles and databases as the local environment: the
# application role must not be a superuser, or row-level security
@@ -136,6 +184,15 @@ jobs:
- name: Test
# Integration tests share one database, so packages run one at a time.
run: go test -p 1 -count=1 ./...
- name: Save caches
if: github.ref == 'refs/heads/main'
uses: actions/cache/save@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.npm
key: test-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
build:
# Nothing is built or pushed from code that fails lint or tests; the
@@ -155,8 +212,20 @@ jobs:
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz
echo /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/go/bin" >> "$GITHUB_PATH"
echo "GO_VERSION=$v" >> "$GITHUB_ENV"
- name: Restore caches
uses: actions/cache/restore@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.npm
key: build-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
restore-keys: |
build-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-
build-go${{ env.GO_VERSION }}-
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
run: npm ci --no-audit --no-fund --prefer-offline && npm run build
- name: Build binaries
id: binaries
run: |
@@ -199,38 +268,59 @@ jobs:
./image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \
-env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $variant $flags
done
- name: Save caches
if: github.ref == 'refs/heads/main'
uses: actions/cache/save@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.npm
key: build-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
# The image job packs the amd64 binaries instead of compiling everything again.
- name: Hand the binaries to the image job
uses: actions/upload-artifact@v4
with:
name: image-context
path: |
Dockerfile.ci
dist/linux_amd64/
retention-days: 1
image:
# Kaniko runs rootless from docker:cli, the same way as the other
# repositories on this instance: the default job image has no docker
# CLI, and Kaniko's own image lacks what the runner needs to keep a job
# container alive. Images are pushed only from main and tags, and only
# once the PACKAGE_TOKEN secret (write:package) exists.
# Builds Dockerfile.ci (the build job's amd64 binaries on distroless)
# with the runner's Docker daemon instead of Kaniko rebuilding frontend
# and Go from the git context. Images are pushed only from main and tags,
# and only once the PACKAGE_TOKEN secret (write:package) exists.
# The build job's version, so the API reports the release its agent
# images are tagged with.
needs: build
runs-on: ubuntu-latest
# Node for the artifact action; the Docker CLI is added below.
container:
image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d
image: node:24-alpine
defaults:
run:
shell: sh
steps:
- uses: actions/download-artifact@v4
with:
name: image-context
path: ctx
- name: Build (and push from main and tags)
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
VERSION: ${{ needs.build.outputs.version }}
run: |
set -eu
apk add --no-cache docker-cli docker-cli-buildx >/dev/null
REGISTRY="${GITHUB_SERVER_URL#*://}"
IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')"
SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)"
TAG="$VERSION"
PUSH="--no-push"
DEST="--destination ${IMAGE}:${TAG#v}"
TAGS="${IMAGE}:${TAG#v}"
# Channels: edge follows main, beta the newest prerelease, latest
# and stable the newest release, X.Y its newest patch.
CHANNELS=""
case "$GITHUB_REF" in
refs/heads/main) CHANNELS="edge" ;;
refs/tags/v*-beta.*) CHANNELS="beta" ;;
@@ -238,33 +328,17 @@ jobs:
MINOR="$(printf '%s' "${TAG#v}" | cut -d. -f1-2)"
CHANNELS="latest stable $MINOR" ;;
esac
for c in $CHANNELS; do TAGS="$TAGS ${IMAGE}:$c"; done
set --
for t in $TAGS; do set -- "$@" -t "$t"; done
docker build --platform linux/amd64 -f ctx/Dockerfile.ci "$@" ctx
case "$GITHUB_REF" in
refs/heads/main|refs/tags/v*)
if [ -n "${PACKAGE_TOKEN:-}" ]; then
PUSH=""
for c in $CHANNELS; do DEST="$DEST --destination ${IMAGE}:$c"; done
else
echo "PACKAGE_TOKEN is not set; building without pushing."
fi ;;
if [ -z "${PACKAGE_TOKEN:-}" ]; then
echo "PACKAGE_TOKEN is not set; built without pushing."
exit 0
fi
printf '%s' "$PACKAGE_TOKEN" | docker login "$REGISTRY" -u "$GITHUB_ACTOR" --password-stdin
for t in $TAGS; do docker push "$t"; done ;;
*) echo "Pull request: built without pushing." ;;
esac
case "$GITHUB_SERVER_URL" in https://*) PULL=https ;; *) PULL=http ;; esac
# Pull requests are built from their head, which Gitea exposes as
# refs/pull/<n>/head.
REF="$GITHUB_REF"
case "$REF" in refs/pull/*/merge) REF="${REF%/merge}/head" ;; esac
AUTH="$(printf '%s:%s' "$GITHUB_ACTOR" "${PACKAGE_TOKEN:-none}" | base64 | tr -d '\n')"
CFG="$(printf '{"auths":{"%s":{"auth":"%s"}}}' "$REGISTRY" "$AUTH")"
docker run --rm \
-e GIT_PULL_METHOD="$PULL" \
-e GIT_USERNAME="x-access-token" \
-e GIT_PASSWORD="$GITEA_TOKEN" \
-e CFG="$CFG" \
--entrypoint /busybox/sh \
gcr.io/kaniko-project/executor:v1.23.2-debug \
-c 'mkdir -p /kaniko/.docker && printf %s "$CFG" > /kaniko/.docker/config.json && exec /kaniko/executor "$@"' _ \
--context "git://${REGISTRY}/${GITHUB_REPOSITORY}.git#${REF}" \
--dockerfile Dockerfile \
--build-arg VERSION="$TAG" \
--build-arg COMMIT="$SHORT" \
$DEST $PUSH \
--compressed-caching=false
+14 -1
View File
@@ -20,6 +20,19 @@ jobs:
v="$(awk '/^go /{print $2}' go.mod)"
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz
echo /usr/local/go/bin >> "$GITHUB_PATH"
echo "GO_VERSION=$v" >> "$GITHUB_ENV"
# Read-only: the ci workflow's build job saves these caches on main.
- name: Restore caches
uses: actions/cache/restore@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.npm
key: build-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-${{ github.sha }}
restore-keys: |
build-go${{ env.GO_VERSION }}-${{ hashFiles('go.sum', 'package-lock.json') }}-
build-go${{ env.GO_VERSION }}-
- name: Check tag
run: |
go run ./tools/release check "$GITHUB_REF_NAME"
@@ -32,7 +45,7 @@ jobs:
exit 1
fi
- name: Build frontend
run: npm ci --no-audit --no-fund && npm run build
run: npm ci --no-audit --no-fund --prefer-offline && npm run build
- name: Package Helm chart
run: |
curl -fsSL "https://get.helm.sh/helm-v3.19.0-linux-amd64.tar.gz" | tar -xz -C /usr/local/bin --strip-components=1 linux-amd64/helm
+7
View File
@@ -0,0 +1,7 @@
# CI image: packs the binaries the build job already compiled (dist/linux_amd64)
# instead of building frontend and Go a second time. `make image` and local
# builds keep using Dockerfile, which builds everything from source.
FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab
COPY dist/linux_amd64/ /usr/local/bin/
USER nonroot
ENTRYPOINT ["/usr/local/bin/api"]
+13 -1
View File
@@ -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.
+3 -2
View File
@@ -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)
+69 -19
View File
@@ -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
}
}
+19
View File
@@ -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)
}
}
}
+74
View File
@@ -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)
}
}
+4
View File
@@ -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, ",") {