Compare commits

..
4 Commits
Author SHA1 Message Date
Sebi efd2f2d793 Merge pull request 'fix(statuspages): encode a page once for all servers, gzipped' (#178) from fix/page-snapshot-memory into main
release / release (push) In progress
ci / lint (push) Successful in 6m30s
ci / image (push) Waiting for needed jobs
ci / test (push) In progress
ci / build (push) In progress
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 / image (pull_request) Waiting for needed jobs
ci / lint (pull_request) Successful in 11m55s
ci / test (pull_request) Successful in 13m30s
ci / build (pull_request) In progress
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
11 changed files with 398 additions and 66 deletions

No files matched your search

+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)
+7 -3
View File
@@ -222,7 +222,8 @@ 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 {
internalError(c, err)
return
@@ -412,8 +413,11 @@ func truncateValid(s string, n int) string {
}
// resultClaimTTL covers the retries of a checker that lost the answer to a
// report, which happen within minutes.
const resultClaimTTL = 2 * time.Hour
// report: the next report, seconds later, or the first after the API is
// 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
// the answer to a report, say because the connection broke while the API was
+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)
}
}
+13 -1
View File
@@ -27,6 +27,7 @@ type Metrics struct {
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
dispatched prometheus.Counter
stale prometheus.Counter
results *prometheus.CounterVec
rejected *prometheus.CounterVec
resultDelay prometheus.Histogram
@@ -62,6 +63,10 @@ func New(edition string) *Metrics {
Namespace: namespace, Name: "checks_dispatched_total",
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{
Namespace: namespace, Name: "check_results_total",
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{}),
build,
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.incidents,
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.
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.
func (m *Metrics) Result(region string, ok bool, delay time.Duration) {
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) {
m := New("cloud")
m.Dispatched(3)
m.Stale(2)
m.Stale(0)
m.Result("fsn", true, 2*time.Second)
m.Result("fsn", false, -time.Second)
m.Rejected("duplicate", 2)
@@ -79,6 +81,7 @@ func TestCountersAndHandler(t *testing.T) {
got, want float64
}{
"dispatched": {testutil.ToFloat64(m.dispatched), 3},
"stale": {testutil.ToFloat64(m.stale), 2},
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
"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.
func acceptsGzip(header string) bool {
for _, part := range strings.Split(header, ",") {
+100 -35
View File
@@ -68,6 +68,9 @@ func New(rdb redis.UniversalClient) *Scheduler {
type Entry struct {
MonitorID uuid.UUID
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.
@@ -267,7 +270,7 @@ for i = 1, #due, 2 do
redis.call('ZREM', KEYS[1], m)
else
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])
local nxt
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
@@ -324,48 +327,100 @@ func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.U
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
// first one. It returns within about a second once ctx is done, so long polls
// do not hold up shutdown or cancelled requests.
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) {
// do not hold up shutdown or cancelled requests. Runs queued for longer than
// 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 {
return nil, nil
return nil, 0, nil
}
q := jobsPrefix + instance.String()
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
}
deadline := time.Now().Add(wait)
for len(raw) == 0 && ctx.Err() == nil {
left := time.Until(deadline)
if left <= 0 {
return nil, nil
stale := 0
for ctx.Err() == nil {
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, stale, err
}
// BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.blpop(ctx, min(left, time.Second), q)
if errors.Is(err, redis.Nil) {
continue
}
if err != nil {
return nil, err
}
raw = []string{first[1]}
if max > 1 {
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
if len(raw) == 0 {
left := time.Until(deadline)
if left <= 0 {
return nil, stale, nil
}
raw = append(raw, more...)
// BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.blpop(ctx, min(left, time.Second), q)
if errors.Is(err, redis.Nil) {
continue
}
if err != nil {
return nil, stale, err
}
raw = []string{first[1]}
if max > 1 {
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, stale, err
}
raw = append(raw, more...)
}
}
out, n, err := s.fresh(ctx, raw)
if err != nil {
return nil, stale, err
}
stale += n
if len(out) > 0 {
return out, stale, nil
}
}
out := make([]Entry, 0, len(raw))
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 {
if e, ok := parseEntry(r); ok {
out = append(out, e)
entries = append(entries, e)
if !e.DispatchedAt.IsZero() {
ids = append(ids, e.MonitorID.String())
}
}
}
return out, nil
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)
}
return out, len(entries) - len(out), nil
}
// 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)
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
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
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()
}
// 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) {
id, at, ok := strings.Cut(s, "|")
if !ok {
parts := strings.Split(s, "|")
if len(parts) < 2 || len(parts) > 3 {
return Entry{}, false
}
mid, err := uuid.Parse(id)
mid, err := uuid.Parse(parts[0])
if err != nil {
return Entry{}, false
}
ms, err := strconv.ParseFloat(at, 64)
ms, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
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 {
t.Helper()
e, err := s.Take(context.Background(), inst, 1000, 0)
e, _, err := s.Take(context.Background(), inst, 1000, 0)
if err != nil {
t.Fatalf("Take() failed: %v", err)
}
@@ -196,7 +196,7 @@ func TestTakeWaits(t *testing.T) {
ctx := context.Background()
in := uuid.New()
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 {
t.Fatalf("Take() on empty queue = %v, %v", got, err)
}
@@ -214,7 +214,7 @@ func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
time.Sleep(100 * time.Millisecond)
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 {
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())
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
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 {
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 {
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)
}
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)
}
}
}