Compare commits

...
14 Commits
Author SHA1 Message Date
Sebi dfa7976c4e fix(deps): update module github.com/twmb/franz-go/pkg/kmsg to v1.15.3
renovate/stability-days Updates have met minimum release age requirement
ci / lint (push) Skipped
ci / build (pull_request) Successful in 3m58s
ci / image (pull_request) Successful in 28s
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 2m36s
ci / test (pull_request) Successful in 8m11s
2026-12-05 18:13:46 +00:00
Sebi 18eb750ccb Merge pull request 'ci: push the image with crane (plain-HTTP in-cluster registry)' (#185) from ci/image-push-crane into main
ci / lint (push) Successful in 2m29s
ci / build (push) Successful in 6m24s
ci / test (push) Successful in 6m22s
ci / image (push) Successful in 49s
Reviewed-on: #185
2026-12-05 17:17:42 +00:00
Sebastian UnterschützandClaude Opus 5.5 266dec50de ci: push the image with crane (plain-HTTP in-cluster registry)
ci / test (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 1m5s
ci / lint (push) Skipped
ci / test (pull_request) Successful in 7m15s
ci / build (push) Skipped
ci / build (pull_request) Successful in 2m25s
ci / image (pull_request) Successful in 28s
On main and tags GITHUB_SERVER_URL is http://gitea-http.gitea.svc...,
and the runner's Docker daemon refused to push there: "server gave HTTP
response to HTTPS client". crane pushes the saved image with --insecure
for http:// servers and tags the channels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:02:53 +01:00
Sebi 220bc5f3d8 Merge pull request 'ci: caches, prebuilt linters, image from the built binaries' (#184) from ci/optimize-pipelines into main
ci / lint (push) Successful in 8m30s
ci / test (push) Successful in 16m28s
ci / build (push) Successful in 20m30s
ci / image (push) Failing after 29s
Reviewed-on: #184
2026-12-05 16:16:10 +00:00
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
Sebi 3bc927a5f7 Merge pull request 'fix(schedule): drop runs left queued for too long; shorter result claims' (#177) from fix/stale-runs-claim-ttl into main
ci / lint (push) Successful in 10m50s
ci / build (push) Successful in 20m23s
ci / test (push) Successful in 11m9s
release / release (push) Successful in 35m31s
ci / image (push) Successful in 6m3s
2026-11-29 18:43:47 +00:00
Sebastian UnterschützandClaude Opus 5.5 94c529a97e fix(schedule): drop runs left queued for too long; shorter result claims
ci / image (push) Skipped
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (pull_request) Successful in 3m35s
ci / lint (pull_request) Successful in 11m48s
ci / test (pull_request) Successful in 13m35s
ci / build (pull_request) Successful in 10m22s
A checker that fell behind kept working off runs from minutes ago while
dispatch queued newer runs of the same monitors behind them, so a backlog
never shrank: pawhost and realtoxmedia stayed at about 50K overdue checks.
Queued runs now record when they were dispatched, and Take drops runs
that waited longer than two intervals. A newer run of the monitor has
been queued by then, since the next run is due at most one and a half
intervals after a dispatch. uptimesebi_checks_stale_total counts them.

Result claims, one Redis key per check result, lived 2 hours although
retries come within minutes. At about 530 results a second that was
4.5 million keys and 1.1 GiB of the shared Redis. They now live 10
minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 19:41:54 +01:00
Sebi 71219d8031 Merge pull request 'fix(evidence): spread periodic evidence and store a report's in one go' (#176) from fix/evidence-burst into main
ci / build (push) Successful in 18m1s
ci / lint (push) Successful in 6m45s
ci / test (push) Successful in 13m58s
ci / image (push) Successful in 5m24s
release / release (push) Successful in 37m59s
2026-11-29 17:18:02 +00:00
Sebastian UnterschützandClaude Opus 5.5 e26194d260 fix(evidence): spread periodic evidence and store a report's in one go
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 13m0s
ci / test (pull_request) Successful in 13m56s
ci / build (pull_request) Successful in 19m56s
ci / image (pull_request) Successful in 5m50s
Checkers send evidence of healthy checks every 10 minutes, first with
the first result after they start. When checkers restart together, as
after a self-update, every monitor's evidence came in the same minute,
every 10 minutes. The API stored each in a transaction of its own while
the checker waited, reports took up to 36 seconds, the checkers' slots
filled and runs piled up: the overdue waves seen in prod.

Evidence sent for another reason than the period now puts the next
periodic one at a random point of the period, and the API writes all of
a report's evidence in one transaction, with one query each for the
successes to replace and the failures last kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 18:16:05 +01:00
Sebi 61a50ee6f0 Merge pull request 'fix(agent): apply agent settings as they are when jobs are handed out' (#175) from fix/agent-settings-after-poll into main
ci / build (push) Successful in 17m58s
ci / lint (push) Successful in 10m42s
ci / test (push) Successful in 18m29s
release / release (push) Successful in 40m13s
ci / image (push) Successful in 5m24s
2026-11-29 15:40:03 +00:00
Sebastian UnterschützandClaude Opus 5.5 4246e37384 fix(agent): apply agent settings as they are when jobs are handed out
ci / image (push) Skipped
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (push) Skipped
ci / build (pull_request) Successful in 10m26s
ci / lint (pull_request) Successful in 10m46s
ci / test (pull_request) Successful in 8m51s
ci / image (pull_request) Successful in 5m8s
The jobs endpoint read the agent, and with it allow_private, before its
long poll of up to 20 seconds, so jobs handed out afterwards could carry
a setting changed in the meantime and the change only applied a poll
later. It now reads the agent again when the poll returns jobs.

TestCheckerNetwork also waits for two runs at most: the next run after a
monitor's first one is on its phase now, up to one and a half intervals
later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:37:08 +01:00
24 changed files with 774 additions and 131 deletions

No files matched your search

+130 -42
View File
@@ -13,7 +13,10 @@ concurrency:
env: env:
GOLANGCI_LINT_VERSION: v2.15.0 GOLANGCI_LINT_VERSION: v2.15.0
SQLC_VERSION: v1.31.1 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 HELM_VERSION: v3.19.0
SHELLCHECK_VERSION: v0.12.0
jobs: jobs:
lint: lint:
@@ -29,8 +32,24 @@ jobs:
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz 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 /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/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 - 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 - name: Generated code is up to date
run: | run: |
go tool templ generate 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; } run: test -z "$(gofmt -l internal cmd tools deploy)" || { gofmt -l internal cmd tools deploy; exit 1; }
- name: go vet - name: go vet
run: go vet ./... run: go vet ./...
# The release binary instead of `go install`, which compiled the linter
# from source on every run.
- name: golangci-lint - name: golangci-lint
run: | run: |
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION} v="${GOLANGCI_LINT_VERSION#v}"
"$(go env GOPATH)/bin/golangci-lint" run ./... 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 - name: Helm chart
run: | 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 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. # Debian and Raspberry Pi OS; the test renders and checks it.
- name: shellcheck - name: shellcheck
run: | 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' 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: test:
runs-on: ubuntu-latest 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 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 /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/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 - 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 - name: Prepare database
# The same roles and databases as the local environment: the # The same roles and databases as the local environment: the
# application role must not be a superuser, or row-level security # application role must not be a superuser, or row-level security
@@ -136,6 +184,15 @@ jobs:
- name: Test - name: Test
# Integration tests share one database, so packages run one at a time. # Integration tests share one database, so packages run one at a time.
run: go test -p 1 -count=1 ./... 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: build:
# Nothing is built or pushed from code that fails lint or tests; the # 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 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 /usr/local/go/bin >> "$GITHUB_PATH"
echo "$HOME/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 - 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 - name: Build binaries
id: binaries id: binaries
run: | run: |
@@ -199,38 +268,59 @@ jobs:
./image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \ ./image -name statuspage -repo "$host/$owner/uptimesebi-statuspage" -port 8082/tcp \
-env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $variant $flags -env UPTIME_STATUSPAGE_CACHE_DIR=/var/lib/uptimesebi $variant $flags
done 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: image:
# Kaniko runs rootless from docker:cli, the same way as the other # Builds Dockerfile.ci (the build job's amd64 binaries on distroless)
# repositories on this instance: the default job image has no docker # with the runner's Docker daemon and pushes with crane instead of Kaniko rebuilding frontend
# CLI, and Kaniko's own image lacks what the runner needs to keep a job # and Go from the git context. Images are pushed only from main and tags,
# container alive. Images are pushed only from main and tags, and only # and only once the PACKAGE_TOKEN secret (write:package) exists.
# once the PACKAGE_TOKEN secret (write:package) exists.
# The build job's version, so the API reports the release its agent # The build job's version, so the API reports the release its agent
# images are tagged with. # images are tagged with.
needs: build needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Node for the artifact action; the Docker CLI is added below.
container: container:
image: docker:cli@sha256:34507eb5069d8be82c95dd3b6987d4250fd5fee49b82e2509b7d7a7030740d6d image: node:24-alpine
defaults: defaults:
run: run:
shell: sh shell: sh
steps: steps:
- uses: actions/download-artifact@v4
with:
name: image-context
path: ctx
- name: Build (and push from main and tags) - name: Build (and push from main and tags)
env: env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
VERSION: ${{ needs.build.outputs.version }} VERSION: ${{ needs.build.outputs.version }}
run: | run: |
set -eu set -eu
apk add --no-cache docker-cli docker-cli-buildx crane >/dev/null
REGISTRY="${GITHUB_SERVER_URL#*://}" REGISTRY="${GITHUB_SERVER_URL#*://}"
IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')" IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')"
SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)"
TAG="$VERSION" TAG="$VERSION"
PUSH="--no-push" TAGS="${IMAGE}:${TAG#v}"
DEST="--destination ${IMAGE}:${TAG#v}"
# Channels: edge follows main, beta the newest prerelease, latest # Channels: edge follows main, beta the newest prerelease, latest
# and stable the newest release, X.Y its newest patch. # and stable the newest release, X.Y its newest patch.
CHANNELS=""
case "$GITHUB_REF" in case "$GITHUB_REF" in
refs/heads/main) CHANNELS="edge" ;; refs/heads/main) CHANNELS="edge" ;;
refs/tags/v*-beta.*) CHANNELS="beta" ;; refs/tags/v*-beta.*) CHANNELS="beta" ;;
@@ -238,33 +328,31 @@ jobs:
MINOR="$(printf '%s' "${TAG#v}" | cut -d. -f1-2)" MINOR="$(printf '%s' "${TAG#v}" | cut -d. -f1-2)"
CHANNELS="latest stable $MINOR" ;; CHANNELS="latest stable $MINOR" ;;
esac 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 case "$GITHUB_REF" in
refs/heads/main|refs/tags/v*) refs/heads/main|refs/tags/v*)
if [ -n "${PACKAGE_TOKEN:-}" ]; then if [ -z "${PACKAGE_TOKEN:-}" ]; then
PUSH="" echo "PACKAGE_TOKEN is not set; built without pushing."
for c in $CHANNELS; do DEST="$DEST --destination ${IMAGE}:$c"; done exit 0
fi
# crane instead of docker push: on main and tags GITHUB_SERVER_URL is
# the in-cluster plain-HTTP address, which the runner's Docker
# daemon refuses ("server gave HTTP response to HTTPS client").
INSECURE=""
case "$GITHUB_SERVER_URL" in http://*) INSECURE="--insecure" ;; esac
printf '%s' "$PACKAGE_TOKEN" | crane auth login "$REGISTRY" -u "$GITHUB_ACTOR" --password-stdin $INSECURE
FIRST=""
for t in $TAGS; do
if [ -z "$FIRST" ]; then
docker save "$t" -o /tmp/image.tar
crane push $INSECURE /tmp/image.tar "$t"
FIRST="$t"
else else
echo "PACKAGE_TOKEN is not set; building without pushing." crane tag $INSECURE "$FIRST" "${t##*:}"
fi ;; fi
done ;;
*) echo "Pull request: built without pushing." ;;
esac 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)" v="$(awk '/^go /{print $2}' go.mod)"
curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz 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 /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 - name: Check tag
run: | run: |
go run ./tools/release check "$GITHUB_REF_NAME" go run ./tools/release check "$GITHUB_REF_NAME"
@@ -32,7 +45,7 @@ jobs:
exit 1 exit 1
fi fi
- name: Build frontend - 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 - name: Package Helm chart
run: | 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 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"]
+1 -1
View File
@@ -27,7 +27,7 @@ require (
github.com/rabbitmq/amqp091-go v1.17.0 github.com/rabbitmq/amqp091-go v1.17.0
github.com/redis/go-redis/v9 v9.23.0 github.com/redis/go-redis/v9 v9.23.0
github.com/twmb/franz-go v1.22.3 github.com/twmb/franz-go v1.22.3
github.com/twmb/franz-go/pkg/kmsg v1.15.1 github.com/twmb/franz-go/pkg/kmsg v1.15.3
github.com/yuin/goldmark v1.8.7 github.com/yuin/goldmark v1.8.7
go.mongodb.org/mongo-driver/v2 v2.5.0 go.mongodb.org/mongo-driver/v2 v2.5.0
go.uber.org/zap v1.28.0 go.uber.org/zap v1.28.0
+2 -2
View File
@@ -307,8 +307,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/twmb/franz-go v1.22.3 h1:RHe35s34pKefMLyL+ZYJ6mQVtfFZz4zHDHVkTyACur0= github.com/twmb/franz-go v1.22.3 h1:RHe35s34pKefMLyL+ZYJ6mQVtfFZz4zHDHVkTyACur0=
github.com/twmb/franz-go v1.22.3/go.mod h1:OhbFLkvp6GLcN5daC7I4Q2z0W/rFP16HG+gTbe9CDC4= github.com/twmb/franz-go v1.22.3/go.mod h1:OhbFLkvp6GLcN5daC7I4Q2z0W/rFP16HG+gTbe9CDC4=
github.com/twmb/franz-go/pkg/kmsg v1.15.1 h1:3sj7ekbH33t73nsBcHS0wtp/PyMIViHLNItZrE8V9zM= github.com/twmb/franz-go/pkg/kmsg v1.15.3 h1:fMxHkXdd2WvlwHQ08lpL+roFh0CY+Qd22Ksieur76Nc=
github.com/twmb/franz-go/pkg/kmsg v1.15.1/go.mod h1:sGkGxKexpRLBThFHJLjjywcyfkK09qB/g+X+wFWZQ/A= github.com/twmb/franz-go/pkg/kmsg v1.15.3/go.mod h1:sGkGxKexpRLBThFHJLjjywcyfkK09qB/g+X+wFWZQ/A=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
+13 -1
View File
@@ -8,6 +8,7 @@ package agentapi
import ( import (
"bytes" "bytes"
"compress/gzip"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -172,7 +173,18 @@ func (c *Client) doWith(ctx context.Context, method, path string, header http.He
case out == nil: case out == nil:
return 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. // 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 { } else {
q.Set("slug", slug) 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 != "" { if checksum != "" {
h = http.Header{"If-None-Match": {`"` + checksum + `"`}} h.Set("If-None-Match", `"`+checksum+`"`)
} }
var p PageSnapshot var p PageSnapshot
err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p) err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p)
+26 -4
View File
@@ -222,12 +222,31 @@ func (s *Server) agentJobs(c *gin.Context) {
} }
}() }()
} }
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait) entries, stale, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
s.metrics.Stale(stale)
if err != nil && pollCtx.Err() == nil { if err != nil && pollCtx.Err() == nil {
internalError(c, err) internalError(c, err)
return return
} }
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries) agent := agentOf(c)
if len(entries) > 0 {
// The long poll may have waited for a while: settings such as
// allow_private apply to the jobs as they are now.
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
agent, err = q.GetAgentByHash(ctx, HashToken(bearerToken(c)))
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
if err != nil {
internalError(c, err)
return
}
}
jobs, orgs, err := s.resolveJobs(ctx, agent, entries)
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
@@ -394,8 +413,11 @@ func truncateValid(s string, n int) string {
} }
// resultClaimTTL covers the retries of a checker that lost the answer to a // resultClaimTTL covers the retries of a checker that lost the answer to a
// report, which happen within minutes. // report: the next report, seconds later, or the first after the API is
const resultClaimTTL = 2 * time.Hour // back. A claim is one Redis key per result, so the TTL sets how much of
// Redis they take: at 500 results a second, 10 minutes are 300,000 keys,
// about 70 MiB.
const resultClaimTTL = 10 * time.Minute
// claimResults drops results already received. A checker that does not get // claimResults drops results already received. A checker that does not get
// the answer to a report, say because the connection broke while the API was // the answer to a report, say because the connection broke while the API was
+3 -1
View File
@@ -85,7 +85,9 @@ func TestCheckerNetwork(t *testing.T) {
} }
waitResult := func(id string, ok bool, what string) { waitResult := func(id string, ok bool, what string) {
t.Helper() t.Helper()
waitFor(t, 20*time.Second, what, func() bool { // Two runs at most: the one already handed out, then the next on
// the monitor's phase, up to one and a half intervals later.
waitFor(t, 30*time.Second, what, func() bool {
got, msg, seen := latestOf(owner, id) got, msg, seen := latestOf(owner, id)
return seen && got == ok && (ok || strings.Contains(msg, "non-public")) return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
}) })
+60 -13
View File
@@ -37,9 +37,15 @@ const (
// storeEvidence keeps the evidence of accepted results: per monitor and // storeEvidence keeps the evidence of accepted results: per monitor and
// region the latest success, and failures unless an identical one was kept // region the latest success, and failures unless an identical one was kept
// within failureEvidenceEvery. Evidence is an aid; failures are logged and // within failureEvidenceEvery. All of a report's evidence is written in one
// never fail the report. // transaction, so a report full of it stays quick and the checker can go
// on. Evidence is an aid; failures are logged and never fail the report.
func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) { func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
var (
successes = map[uuid.UUID]agentapi.Result{}
failures []agentapi.Result
failed []uuid.UUID
)
for _, r := range results { for _, r := range results {
m, ok := monitors[r.MonitorID] m, ok := monitors[r.MonitorID]
if len(r.Evidence) == 0 || !ok { if len(r.Evidence) == 0 || !ok {
@@ -49,20 +55,24 @@ func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.
s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence)) s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence))
continue continue
} }
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if r.OK { if r.OK {
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil { // Only the latest success is kept anyway.
return err if prev, seen := successes[r.MonitorID]; !seen || r.StartedAt.After(prev.StartedAt) {
successes[r.MonitorID] = r
} }
} else { continue
last, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{MonitorID: m.ID, Region: region})
if err == nil && last.Error == r.Error && r.StartedAt.Sub(last.Time) < failureEvidenceEvery {
return nil
} }
if err != nil && !errors.Is(err, pgx.ErrNoRows) { failures = append(failures, r)
return err if !slices.Contains(failed, r.MonitorID) {
failed = append(failed, r.MonitorID)
} }
} }
if len(successes) == 0 && len(failures) == 0 {
return
}
slices.SortFunc(failures, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
insert := func(q *store.Queries, r agentapi.Result) error {
m := monitors[r.MonitorID]
row := store.InsertEvidenceParams{ row := store.InsertEvidenceParams{
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence, OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
} }
@@ -73,10 +83,47 @@ func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.
row.Error = ptr(truncateValid(r.Error, 500)) row.Error = ptr(truncateValid(r.Error, 500))
} }
return q.InsertEvidence(ctx, row) return q.InsertEvidence(ctx, row)
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if len(successes) > 0 {
ids := make([]uuid.UUID, 0, len(successes))
for id := range successes {
ids = append(ids, id)
}
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{Region: region, MonitorIds: ids}); err != nil {
return err
}
for _, r := range successes {
if err := insert(q, r); err != nil {
return err
}
}
}
if len(failures) == 0 {
return nil
}
rows, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{Region: region, MonitorIds: failed})
if err != nil {
return err
}
last := make(map[uuid.UUID]store.LastFailureEvidenceRow, len(rows))
for _, l := range rows {
last[l.MonitorID] = l
}
for _, r := range failures {
kept := truncateValid(r.Error, 500)
if l, ok := last[r.MonitorID]; ok && l.Error == kept && r.StartedAt.Sub(l.Time) < failureEvidenceEvery {
continue
}
if err := insert(q, r); err != nil {
return err
}
last[r.MonitorID] = store.LastFailureEvidenceRow{MonitorID: r.MonitorID, Time: r.StartedAt, Error: kept}
}
return nil
}) })
if err != nil { if err != nil {
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err) s.log.WarnContext(ctx, "storing evidence failed", "results", len(successes)+len(failures), "error", err)
}
} }
} }
+64
View File
@@ -2,12 +2,17 @@ package api_test
import ( import (
"context" "context"
"encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
) )
func TestEvidence(t *testing.T) { func TestEvidence(t *testing.T) {
@@ -103,3 +108,62 @@ func TestEvidence(t *testing.T) {
t.Error("the monitor page links evidence for a viewer") t.Error("the monitor page links evidence for a viewer")
} }
} }
// TestEvidenceBatch stores a report with evidence of several monitors and
// runs at once, as a checker sends after a backlog.
func TestEvidenceBatch(t *testing.T) {
e := newEnv(t)
tok, region := e.platformChecker(t, uniq("ev-batch-"))
owner := e.browser(t)
owner.signup("o@"+uniq("evb")+".test", uniq("evb-"))
monitor := func() uuid.UUID {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
return uuid.MustParse(m["id"].(string))
}
up, down := monitor(), monitor()
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
ev := json.RawMessage(`{"steps":[]}`)
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
run := func(m uuid.UUID, after time.Duration, ok bool, msg string) agentapi.Result {
return agentapi.Result{MonitorID: m, ScheduledAt: at.Add(after), StartedAt: at.Add(after), OK: ok, Error: msg, Evidence: ev}
}
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 0, true, ""),
run(up, time.Second, true, ""),
run(down, 0, false, "boom"),
run(down, time.Second, false, "boom"),
run(down, 2*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
// The latest success only; failures unless the same one was just kept.
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(time.Second)); n != 1 {
t.Errorf("success evidence of the latest run = %d rows, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows = %d, want 2: boom once, then other", n)
}
// The next report replaces the success and thins out the failure
// already kept.
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 5*time.Second, true, ""),
run(down, 10*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(5*time.Second)); n != 1 {
t.Errorf("success evidence after the next report: latest run kept %d times, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows after the next report = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows after the next report = %d, want still 2", n)
}
}
+69 -19
View File
@@ -1,6 +1,8 @@
package api package api
import ( import (
"bytes"
"compress/gzip"
"context" "context"
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
@@ -24,6 +26,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "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/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate" "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/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web" "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{ comp := agentapi.Component{
ID: m.MonitorID.String(), ID: m.MonitorID.String(),
Name: name, Name: name,
Uptime: uptime90, Uptime: roundRatio(uptime90),
Days: dayHistory(days[m.MonitorID], now), Days: dayHistory(days[m.MonitorID], now),
} }
switch { switch {
@@ -308,7 +311,7 @@ func buildComponentDetails(
ts := endHour.Add(-time.Duration(23-i) * time.Hour) ts := endHour.Add(-time.Duration(23-i) * time.Hour)
hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1} hours[i] = agentapi.HourBucket{Time: ts, Uptime: -1}
if b, ok := byHour[ts.Unix()]; ok && b.Total > 0 { 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))) 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) }) slices.SortFunc(regs, func(a, b agentapi.ComponentRegion) int { return strings.Compare(a.Name, b.Name) })
return &agentapi.ComponentDetails{ return &agentapi.ComponentDetails{
SLA24h: web.Uptime(hourly), SLA24h: roundRatio(web.Uptime(hourly)),
SLA7d: web.Uptime(d7), SLA7d: roundRatio(web.Uptime(d7)),
SLA30d: web.Uptime(d30), SLA30d: roundRatio(web.Uptime(d30)),
SLA90d: uptime90, SLA90d: roundRatio(uptime90),
Hours: hours, Hours: hours,
Regions: regs, 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) d := start.AddDate(0, 0, i).Format(time.DateOnly)
out[i] = agentapi.Day{Date: d, Uptime: -1} out[i] = agentapi.Day{Date: d, Uptime: -1}
if b, ok := byDay[d]; ok && b.Total > 0 { 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 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 // agentPage serves a page snapshot to status page servers. Org-owned
// servers only receive their own org's pages. // servers only receive their own org's pages.
func (s *Server) agentPage(c *gin.Context) { 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 // The server sends the checksum of its copy; an unchanged page is not
// sent again. // sent again.
etag := `"` + snap.Checksum() + `"` c.Header("ETag", snap.etag)
c.Header("ETag", etag) if c.GetHeader("If-None-Match") == snap.etag {
if c.GetHeader("If-None-Match") == etag {
c.Status(http.StatusNotModified) c.Status(http.StatusNotModified)
return 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 // snapshotTimeout bounds a shared snapshot build, which outlives the
// request that started it. // request that started it.
const snapshotTimeout = time.Minute const snapshotTimeout = time.Minute
// sharedSnapshot builds page once for all status page servers asking for it // sharedSnapshot builds and encodes page once for all status page servers
// at the same time, as they do when told that it changed. A server giving // asking for it at the same time, as they do when told that it changed. A
// up does not cancel the build for the others. // server giving up does not cancel the build for the others.
func (s *Server) sharedSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) { func (s *Server) sharedSnapshot(ctx context.Context, page store.StatusPage) (encodedSnapshot, error) {
ch := s.snapshots.DoChan(page.ID.String(), func() (any, error) { ch := s.snapshots.DoChan(page.ID.String(), func() (any, error) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), snapshotTimeout) ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), snapshotTimeout)
defer cancel() defer cancel()
return s.buildSnapshot(ctx, page) snap, err := s.buildSnapshot(ctx, page)
if err != nil {
return nil, err
}
return encodeSnapshot(snap)
}) })
select { select {
case <-ctx.Done(): case <-ctx.Done():
return agentapi.PageSnapshot{}, ctx.Err() return encodedSnapshot{}, ctx.Err()
case r := <-ch: case r := <-ch:
if r.Err != nil { 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 package api_test
import ( import (
"compress/gzip"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -9,6 +10,7 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"slices" "slices"
"strconv"
"strings" "strings"
"testing" "testing"
"time" "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)
}
}
+16 -2
View File
@@ -8,6 +8,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"log/slog" "log/slog"
"math/rand/v2"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
@@ -51,6 +52,8 @@ type Runner struct {
evidenceMu sync.Mutex evidenceMu sync.Mutex
evidence map[uuid.UUID]evidenceState evidence map[uuid.UUID]evidenceState
// jitter returns a random duration in [0, d), replaced in tests.
jitter func(d time.Duration) time.Duration
} }
// evidenceState remembers what was last sent for a monitor. // evidenceState remembers what was last sent for a monitor.
@@ -66,13 +69,23 @@ const evidenceEvery = 10 * time.Minute
// shouldSendEvidence decides whether a result carries its evidence: every // shouldSendEvidence decides whether a result carries its evidence: every
// failure, every change between success and failure, and otherwise every // failure, every change between success and failure, and otherwise every
// evidenceEvery. Most results thus stay small. // evidenceEvery. Most results thus stay small.
//
// Evidence sent for another reason than the period, like the first result
// after a start, puts the next periodic one at a random point of the
// period. Otherwise every monitor would send its evidence in the same
// minute every period after a restart, and the API would have to store all
// of it at once.
func (r *Runner) shouldSendEvidence(monitor uuid.UUID, ok bool, now time.Time) bool { func (r *Runner) shouldSendEvidence(monitor uuid.UUID, ok bool, now time.Time) bool {
r.evidenceMu.Lock() r.evidenceMu.Lock()
defer r.evidenceMu.Unlock() defer r.evidenceMu.Unlock()
last, seen := r.evidence[monitor] last, seen := r.evidence[monitor]
send := !ok || !seen || last.ok != ok || now.Sub(last.sent) >= evidenceEvery periodic := seen && last.ok == ok && now.Sub(last.sent) >= evidenceEvery
if send { send := !ok || !seen || last.ok != ok || periodic
switch {
case periodic:
last.sent = now last.sent = now
case send:
last.sent = now.Add(-r.jitter(evidenceEvery))
} }
last.ok = ok last.ok = ok
r.evidence[monitor] = last r.evidence[monitor] = last
@@ -90,6 +103,7 @@ func New(api API, concurrency int, log *slog.Logger) *Runner {
results: make(chan agentapi.Result, 1024), results: make(chan agentapi.Result, 1024),
evidence: map[uuid.UUID]evidenceState{}, evidence: map[uuid.UUID]evidenceState{},
jitter: rand.N[time.Duration],
} }
} }
+37
View File
@@ -10,6 +10,7 @@ import (
func TestEvidencePolicy(t *testing.T) { func TestEvidencePolicy(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler)) r := New(nil, 1, slog.New(slog.DiscardHandler))
r.jitter = func(time.Duration) time.Duration { return 0 }
m := uuid.New() m := uuid.New()
now := time.Now() now := time.Now()
steps := []struct { steps := []struct {
@@ -31,3 +32,39 @@ func TestEvidencePolicy(t *testing.T) {
} }
} }
} }
// TestEvidenceSpreadsAfterStart starts with many healthy monitors at once:
// their periodic evidence must not all fall into the same minute again.
func TestEvidenceSpreadsAfterStart(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler))
start := time.Now()
const monitors = 600
ids := make([]uuid.UUID, monitors)
for i := range ids {
ids[i] = uuid.New()
if !r.shouldSendEvidence(ids[i], true, start) {
t.Fatal("first result sent no evidence")
}
}
// One result per monitor and minute over the next period.
perMinute := map[int]int{}
for minute := 1; minute <= int(evidenceEvery/time.Minute); minute++ {
for _, id := range ids {
if r.shouldSendEvidence(id, true, start.Add(time.Duration(minute)*time.Minute)) {
perMinute[minute]++
}
}
}
total, peak := 0, 0
for _, n := range perMinute {
total += n
peak = max(peak, n)
}
if total != monitors {
t.Errorf("periodic evidence in the first period = %d, want one per monitor, %d", total, monitors)
}
// 60 a minute on average; all 600 in one minute without the jitter.
if peak > 150 {
t.Errorf("busiest minute sent %d evidence, want them spread at about %d a minute", peak, monitors/10)
}
}
+13 -1
View File
@@ -27,6 +27,7 @@ type Metrics struct {
duration *prometheus.HistogramVec duration *prometheus.HistogramVec
inFlight prometheus.Gauge inFlight prometheus.Gauge
dispatched prometheus.Counter dispatched prometheus.Counter
stale prometheus.Counter
results *prometheus.CounterVec results *prometheus.CounterVec
rejected *prometheus.CounterVec rejected *prometheus.CounterVec
resultDelay prometheus.Histogram resultDelay prometheus.Histogram
@@ -62,6 +63,10 @@ func New(edition string) *Metrics {
Namespace: namespace, Name: "checks_dispatched_total", Namespace: namespace, Name: "checks_dispatched_total",
Help: "Checks this instance moved from the schedule to the checkers' queues.", Help: "Checks this instance moved from the schedule to the checkers' queues.",
}), }),
stale: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace, Name: "checks_stale_total",
Help: "Queued checks dropped because they waited longer than two intervals; a newer run of the monitor was queued by then.",
}),
results: prometheus.NewCounterVec(prometheus.CounterOpts{ results: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "check_results_total", Namespace: namespace, Name: "check_results_total",
Help: "Check results stored, by region (\"own\" for organizations' own checkers) and outcome.", Help: "Check results stored, by region (\"own\" for organizations' own checkers) and outcome.",
@@ -116,7 +121,7 @@ func New(edition string) *Metrics {
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
build, build,
m.requests, m.duration, m.inFlight, m.requests, m.duration, m.inFlight,
m.dispatched, m.results, m.rejected, m.resultDelay, m.dispatched, m.stale, m.results, m.rejected, m.resultDelay,
m.notifications, m.notifyDuration, m.subscriberMail, m.notifications, m.notifyDuration, m.subscriberMail,
m.incidents, m.incidents,
m.jobRuns, m.jobDuration, m.jobSuccess, m.jobRuns, m.jobDuration, m.jobSuccess,
@@ -162,6 +167,13 @@ func (m *Metrics) HTTP(streaming ...string) gin.HandlerFunc {
// Dispatched counts checks moved to the checkers' queues. // Dispatched counts checks moved to the checkers' queues.
func (m *Metrics) Dispatched(n int) { m.dispatched.Add(float64(n)) } func (m *Metrics) Dispatched(n int) { m.dispatched.Add(float64(n)) }
// Stale counts n queued checks dropped as out of date.
func (m *Metrics) Stale(n int) {
if n > 0 {
m.stale.Add(float64(n))
}
}
// Result counts a stored check result and how long it took to arrive. // Result counts a stored check result and how long it took to arrive.
func (m *Metrics) Result(region string, ok bool, delay time.Duration) { func (m *Metrics) Result(region string, ok bool, delay time.Duration) {
m.results.WithLabelValues(region, strconv.FormatBool(ok)).Inc() m.results.WithLabelValues(region, strconv.FormatBool(ok)).Inc()
+3
View File
@@ -66,6 +66,8 @@ func TestJobRecordsOutcome(t *testing.T) {
func TestCountersAndHandler(t *testing.T) { func TestCountersAndHandler(t *testing.T) {
m := New("cloud") m := New("cloud")
m.Dispatched(3) m.Dispatched(3)
m.Stale(2)
m.Stale(0)
m.Result("fsn", true, 2*time.Second) m.Result("fsn", true, 2*time.Second)
m.Result("fsn", false, -time.Second) m.Result("fsn", false, -time.Second)
m.Rejected("duplicate", 2) m.Rejected("duplicate", 2)
@@ -79,6 +81,7 @@ func TestCountersAndHandler(t *testing.T) {
got, want float64 got, want float64
}{ }{
"dispatched": {testutil.ToFloat64(m.dispatched), 3}, "dispatched": {testutil.ToFloat64(m.dispatched), 3},
"stale": {testutil.ToFloat64(m.stale), 2},
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1}, "ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1}, "failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
"duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2}, "duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2},
+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. // acceptsGzip reports whether an Accept-Encoding header allows gzip.
func acceptsGzip(header string) bool { func acceptsGzip(header string) bool {
for _, part := range strings.Split(header, ",") { for _, part := range strings.Split(header, ",") {
+84 -19
View File
@@ -68,6 +68,9 @@ func New(rdb redis.UniversalClient) *Scheduler {
type Entry struct { type Entry struct {
MonitorID uuid.UUID MonitorID uuid.UUID
ScheduledAt time.Time ScheduledAt time.Time
// DispatchedAt is when the run was queued; zero for runs queued before
// dispatch times were recorded.
DispatchedAt time.Time
} }
// Monitor is the schedule-relevant part of a monitor. // Monitor is the schedule-relevant part of a monitor.
@@ -267,7 +270,7 @@ for i = 1, #due, 2 do
redis.call('ZREM', KEYS[1], m) redis.call('ZREM', KEYS[1], m)
else else
local q = ARGV[4] .. live[math.random(#live)] local q = ARGV[4] .. live[math.random(#live)]
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at)) redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at) .. '|' .. string.format('%.0f', now))
redis.call('EXPIRE', q, ARGV[5]) redis.call('EXPIRE', q, ARGV[5])
local nxt local nxt
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '') local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
@@ -324,23 +327,33 @@ func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.U
return time.UnixMilli(int64(score)), err return time.UnixMilli(int64(score)), err
} }
// staleAfter is how many intervals a queued run may wait before Take drops
// it. By then a newer run of the monitor has been dispatched, since the next
// run is due at most one and a half intervals after the last dispatch, so
// a checker that fell behind catches up instead of working off runs that
// are out of date.
const staleAfter = 2
// Take pops up to max queued runs for instance, waiting up to wait for the // Take pops up to max queued runs for instance, waiting up to wait for the
// first one. It returns within about a second once ctx is done, so long polls // first one. It returns within about a second once ctx is done, so long polls
// do not hold up shutdown or cancelled requests. // do not hold up shutdown or cancelled requests. Runs queued for longer than
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) { // staleAfter intervals are dropped; Take returns how many.
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, int, error) {
if max <= 0 { if max <= 0 {
return nil, nil return nil, 0, nil
} }
q := jobsPrefix + instance.String() q := jobsPrefix + instance.String()
deadline := time.Now().Add(wait)
stale := 0
for ctx.Err() == nil {
raw, err := s.rdb.LPopCount(ctx, q, max).Result() raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) { if err != nil && !errors.Is(err, redis.Nil) {
return nil, err return nil, stale, err
} }
deadline := time.Now().Add(wait) if len(raw) == 0 {
for len(raw) == 0 && ctx.Err() == nil {
left := time.Until(deadline) left := time.Until(deadline)
if left <= 0 { if left <= 0 {
return nil, nil return nil, stale, nil
} }
// BLPOP blocks server side and ignores ctx, so wait in slices. // BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.blpop(ctx, min(left, time.Second), q) first, err := s.blpop(ctx, min(left, time.Second), q)
@@ -348,24 +361,66 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
continue continue
} }
if err != nil { if err != nil {
return nil, err return nil, stale, err
} }
raw = []string{first[1]} raw = []string{first[1]}
if max > 1 { if max > 1 {
more, err := s.rdb.LPopCount(ctx, q, max-1).Result() more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
if err != nil && !errors.Is(err, redis.Nil) { if err != nil && !errors.Is(err, redis.Nil) {
return nil, err return nil, stale, err
} }
raw = append(raw, more...) raw = append(raw, more...)
} }
} }
out := make([]Entry, 0, len(raw)) out, n, err := s.fresh(ctx, raw)
if err != nil {
return nil, stale, err
}
stale += n
if len(out) > 0 {
return out, stale, nil
}
}
return nil, stale, nil
}
// fresh parses popped runs and drops those queued for longer than
// staleAfter intervals. It returns the rest and how many it dropped.
func (s *Scheduler) fresh(ctx context.Context, raw []string) ([]Entry, int, error) {
entries := make([]Entry, 0, len(raw))
var ids []string
for _, r := range raw { for _, r := range raw {
if e, ok := parseEntry(r); ok { if e, ok := parseEntry(r); ok {
entries = append(entries, e)
if !e.DispatchedAt.IsZero() {
ids = append(ids, e.MonitorID.String())
}
}
}
if len(ids) == 0 {
return entries, 0, nil
}
vals, err := s.rdb.HMGet(ctx, keyIntervals, ids...).Result()
if err != nil {
return nil, 0, err
}
interval := make(map[uuid.UUID]time.Duration, len(ids))
for i, v := range vals {
str, _ := v.(string)
if ms, err := strconv.ParseInt(str, 10, 64); err == nil {
interval[uuid.MustParse(ids[i])] = time.Duration(ms) * time.Millisecond
}
}
now := s.now()
out := entries[:0]
for _, e := range entries {
// Removed monitors are left to the caller, which drops them.
if iv, ok := interval[e.MonitorID]; ok && !e.DispatchedAt.IsZero() && now.Sub(e.DispatchedAt) > staleAfter*iv {
continue
}
out = append(out, e) out = append(out, e)
} }
} return out, len(entries) - len(out), nil
return out, nil
} }
// blpop is BLPOP with a timeout below a second, which go-redis would round // blpop is BLPOP with a timeout below a second, which go-redis would round
@@ -404,7 +459,7 @@ local cutoff = tonumber(ARGV[1])
local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff) local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff)
for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do
for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do
local at = tonumber(string.sub(job, string.find(job, '|', 1, true) + 1)) local at = tonumber(string.match(job, '^[^|]*|([^|]*)'))
if at ~= nil and at <= cutoff then n = n + 1 end if at ~= nil and at <= cutoff then n = n + 1 end
end end
end end
@@ -419,18 +474,28 @@ func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Durati
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64() s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
} }
// parseEntry parses a queued run: "monitor|scheduled ms|dispatched ms",
// or without the dispatch time as queued by older releases.
func parseEntry(s string) (Entry, bool) { func parseEntry(s string) (Entry, bool) {
id, at, ok := strings.Cut(s, "|") parts := strings.Split(s, "|")
if !ok { if len(parts) < 2 || len(parts) > 3 {
return Entry{}, false return Entry{}, false
} }
mid, err := uuid.Parse(id) mid, err := uuid.Parse(parts[0])
if err != nil { if err != nil {
return Entry{}, false return Entry{}, false
} }
ms, err := strconv.ParseFloat(at, 64) ms, err := strconv.ParseFloat(parts[1], 64)
if err != nil { if err != nil {
return Entry{}, false return Entry{}, false
} }
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true e := Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}
if len(parts) == 3 {
d, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
return Entry{}, false
}
e.DispatchedAt = time.UnixMilli(int64(d))
}
return e, true
} }
+93 -5
View File
@@ -33,7 +33,7 @@ func newTest(t *testing.T) (*Scheduler, *time.Time) {
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry { func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
t.Helper() t.Helper()
e, err := s.Take(context.Background(), inst, 1000, 0) e, _, err := s.Take(context.Background(), inst, 1000, 0)
if err != nil { if err != nil {
t.Fatalf("Take() failed: %v", err) t.Fatalf("Take() failed: %v", err)
} }
@@ -196,7 +196,7 @@ func TestTakeWaits(t *testing.T) {
ctx := context.Background() ctx := context.Background()
in := uuid.New() in := uuid.New()
start := time.Now() start := time.Now()
got, err := s.Take(ctx, in, 10, 300*time.Millisecond) got, _, err := s.Take(ctx, in, 10, 300*time.Millisecond)
if err != nil || len(got) != 0 { if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err) t.Fatalf("Take() on empty queue = %v, %v", got, err)
} }
@@ -214,7 +214,7 @@ func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000") s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
}() }()
got, err := s.Take(ctx, in, 10, 600*time.Millisecond) got, _, err := s.Take(ctx, in, 10, 600*time.Millisecond)
if err != nil || len(got) != 1 || got[0].MonitorID != monitor { if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err) t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
} }
@@ -225,7 +225,7 @@ func TestTakeReturnsWhenCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
go func() { time.Sleep(100 * time.Millisecond); cancel() }() go func() { time.Sleep(100 * time.Millisecond); cancel() }()
start := time.Now() start := time.Now()
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second) _, _, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
if took := time.Since(start); took > 2*time.Second { if took := time.Since(start); took > 2*time.Second {
t.Errorf("Take() returned %v after cancellation, want within about a second", took) t.Errorf("Take() returned %v after cancellation, want within about a second", took)
} }
@@ -282,7 +282,7 @@ func TestOverdueCountsRunsLeftBehind(t *testing.T) {
if n := overdue(); n != 2 { if n := overdue(); n != 2 {
t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n) t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n)
} }
if _, err := s.Take(ctx, busy, 10, 0); err != nil { if _, _, err := s.Take(ctx, busy, 10, 0); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if n := overdue(); n != 0 { if n := overdue(); n != 0 {
@@ -421,3 +421,91 @@ func TestNextSlot(t *testing.T) {
} }
} }
} }
// TestTakeDropsStaleRuns lets a busy instance fall behind: the runs it left
// in its queue for more than two intervals are dropped, the newer ones of
// the same monitors are handed out.
func TestTakeDropsStaleRuns(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
busy := uuid.New()
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
_ = s.Heartbeat(ctx, "eu", busy)
mustDispatch(t, s)
// Within two intervals the run is still handed out.
*now = now.Add(2 * time.Minute)
if got, stale, err := s.Take(ctx, busy, 10, 0); err != nil || len(got) != 1 || stale != 0 {
t.Fatalf("Take() after two intervals = %v, %d stale, %v; want the run", got, stale, err)
}
// Left waiting longer, it is dropped in favour of the newer run.
_ = s.Heartbeat(ctx, "eu", busy)
mustDispatch(t, s)
*now = now.Add(2*time.Minute + time.Second)
_ = s.Heartbeat(ctx, "eu", busy)
if n := mustDispatch(t, s); n != 1 {
t.Fatalf("Dispatch() of the newer run = %d, want 1", n)
}
got, stale, err := s.Take(ctx, busy, 10, 0)
if err != nil {
t.Fatal(err)
}
if stale != 1 || len(got) != 1 || !got[0].DispatchedAt.Equal(*now) {
t.Errorf("Take() = %+v with %d stale, want only the run dispatched now and 1 stale", got, stale)
}
}
// TestTakeSkipsAllStaleRuns does not return empty-handed while fresh runs
// wait behind a batch of stale ones.
func TestTakeSkipsAllStaleRuns(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
for range 5 {
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
}
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
*now = now.Add(3 * time.Minute)
fresh := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, fresh, nil)
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
// The first pop of 5 holds only stale runs.
got, stale, err := s.Take(ctx, in, 5, 0)
if err != nil {
t.Fatal(err)
}
if stale != 5 {
t.Errorf("stale runs = %d, want 5", stale)
}
// It pops on and hands out the next runs, all dispatched now.
if len(got) != 5 {
t.Fatalf("Take() = %d runs, want 5", len(got))
}
for _, e := range got {
if !e.DispatchedAt.Equal(*now) {
t.Errorf("Take() handed out %+v, want only runs dispatched now", e)
}
}
if rest := takeAll(t, s, in); len(rest) != 1 || rest[0].MonitorID != fresh.ID {
t.Errorf("remaining runs = %+v, want the new monitor's", rest)
}
}
func TestParseEntry(t *testing.T) {
id := uuid.New()
if e, ok := parseEntry(id.String() + "|1800000000000"); !ok || !e.DispatchedAt.IsZero() || e.ScheduledAt.UnixMilli() != 1_800_000_000_000 {
t.Errorf("entry without dispatch time = %+v, %v", e, ok)
}
if e, ok := parseEntry(id.String() + "|1800000000000|1800000005000"); !ok || e.DispatchedAt.UnixMilli() != 1_800_000_005_000 {
t.Errorf("entry with dispatch time = %+v, %v", e, ok)
}
for _, bad := range []string{"x|1", id.String(), id.String() + "|1|2|3", id.String() + "|1|x"} {
if _, ok := parseEntry(bad); ok {
t.Errorf("parseEntry(%q) accepted", bad)
}
}
}
+29 -12
View File
@@ -13,17 +13,18 @@ import (
) )
const deleteSuccessEvidence = `-- name: DeleteSuccessEvidence :exec const deleteSuccessEvidence = `-- name: DeleteSuccessEvidence :exec
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok DELETE FROM check_evidence
WHERE region = $1 AND ok AND monitor_id = ANY($2::uuid[])
` `
type DeleteSuccessEvidenceParams struct { type DeleteSuccessEvidenceParams struct {
MonitorID uuid.UUID
Region string Region string
MonitorIds []uuid.UUID
} }
// Only the latest success per monitor and region is kept. // Only the latest success per monitor and region is kept.
func (q *Queries) DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error { func (q *Queries) DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error {
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.MonitorID, arg.Region) _, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.Region, arg.MonitorIds)
return err return err
} }
@@ -124,27 +125,43 @@ func (q *Queries) InsertEvidence(ctx context.Context, arg InsertEvidenceParams)
return err return err
} }
const lastFailureEvidence = `-- name: LastFailureEvidence :one const lastFailureEvidence = `-- name: LastFailureEvidence :many
SELECT time, coalesce(error, '')::text AS error FROM check_evidence SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
WHERE monitor_id = $1 AND region = $2 AND NOT ok FROM check_evidence
ORDER BY time DESC LIMIT 1 WHERE region = $1 AND NOT ok AND monitor_id = ANY($2::uuid[])
ORDER BY monitor_id, time DESC
` `
type LastFailureEvidenceParams struct { type LastFailureEvidenceParams struct {
MonitorID uuid.UUID
Region string Region string
MonitorIds []uuid.UUID
} }
type LastFailureEvidenceRow struct { type LastFailureEvidenceRow struct {
MonitorID uuid.UUID
Time time.Time Time time.Time
Error string Error string
} }
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) { // The newest failure per monitor in region.
row := q.db.QueryRow(ctx, lastFailureEvidence, arg.MonitorID, arg.Region) func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error) {
rows, err := q.db.Query(ctx, lastFailureEvidence, arg.Region, arg.MonitorIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LastFailureEvidenceRow{}
for rows.Next() {
var i LastFailureEvidenceRow var i LastFailureEvidenceRow
err := row.Scan(&i.Time, &i.Error) if err := rows.Scan(&i.MonitorID, &i.Time, &i.Error); err != nil {
return i, err return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
} }
const listEvidence = `-- name: ListEvidence :many const listEvidence = `-- name: ListEvidence :many
+2 -1
View File
@@ -217,7 +217,8 @@ type Querier interface {
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error) InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
IsMember(ctx context.Context, arg IsMemberParams) (bool, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) // The newest failure per monitor in region.
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error)
// latest_results holds the newest check result per monitor and region // latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security. // (see migration 00055) and has row-level security.
// Whether the newest result of each region of the monitors ids succeeded. // Whether the newest result of each region of the monitors ids succeeded.
+8 -5
View File
@@ -4,12 +4,15 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
-- name: DeleteSuccessEvidence :exec -- name: DeleteSuccessEvidence :exec
-- Only the latest success per monitor and region is kept. -- Only the latest success per monitor and region is kept.
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok; DELETE FROM check_evidence
WHERE region = sqlc.arg(region) AND ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[]);
-- name: LastFailureEvidence :one -- name: LastFailureEvidence :many
SELECT time, coalesce(error, '')::text AS error FROM check_evidence -- The newest failure per monitor in region.
WHERE monitor_id = $1 AND region = $2 AND NOT ok SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
ORDER BY time DESC LIMIT 1; FROM check_evidence
WHERE region = sqlc.arg(region) AND NOT ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[])
ORDER BY monitor_id, time DESC;
-- name: ListEvidence :many -- name: ListEvidence :many
-- Newest first, a page from a keyset cursor (see paging.go). -- Newest first, a page from a keyset cursor (see paging.go).