Compare commits

...
9 Commits
Author SHA1 Message Date
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
Sebi 9d1d6a2544 Merge pull request 'feat(schedule): spread monitor runs evenly over their interval' (#174) from feat/schedule-phase into main
ci / lint (push) Successful in 12m50s
ci / test (push) Successful in 13m53s
ci / build (push) Successful in 20m40s
ci / image (push) Successful in 4m21s
release / release (push) Successful in 42m44s
2026-11-29 15:07:46 +00:00
Sebastian UnterschützandClaude Opus 5.5 050c9dd0a1 feat(schedule): spread monitor runs evenly over their interval
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m40s
ci / test (pull_request) Failing after 13m52s
ci / build (pull_request) Skipped
ci / image (pull_request) Skipped
A monitor's next run was its last due time plus the interval, so monitors
created together, by an import or a test, stayed due in the same second
for good, and late runs all gathered at the dispatch time. In prod, regions
fell behind in waves every interval although the checkers kept up on
average.

Each monitor now has a fixed phase within its interval, from its ID.
After the first run, still right away, it runs on its phase; late runs
snap to their next slot. Reconcile adds lost monitors on their phase, so
rebuilding a schedule causes no burst either. Monitors scheduled before
phases existed keep the old rule until reconciliation adds their phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:06:40 +01:00
Sebi 6d4842f4a3 Merge pull request 'fix(checker): take work as soon as a slot frees; alert on overdue checks' (#173) from fix/checker-slot-wait into main
ci / test (push) Successful in 13m12s
ci / lint (push) Successful in 6m46s
ci / build (push) Successful in 17m58s
release / release (push) Successful in 37m25s
ci / image (push) Successful in 6m0s
2026-11-29 13:34:43 +00:00
Sebastian UnterschützandClaude Opus 5.5 2fa439c47d feat(api): count queued runs as overdue; alert rules in the chart
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m57s
ci / test (pull_request) Successful in 13m1s
ci / build (pull_request) Successful in 19m25s
ci / image (pull_request) Successful in 6m9s
uptimesebi_checks_overdue counted only runs not dispatched yet. Dispatch
hands due runs to an instance's queue and schedules the next run at once,
so a checker too busy to take its work left the metric at 0. It now also
counts queued runs due more than 10 seconds ago.

The chart adds an optional PrometheusRule (api.metrics.prometheusRule):
UptimeSebiRegionBehind fires when a region's checks stay overdue, and
UptimeSebiPlatformMetricsFailing when the platform metrics cannot be read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 14:15:49 +01:00
Sebastian UnterschützandClaude Opus 5.5 e776143ee0 fix(checker): take work as soon as a slot frees
With every slot busy, the poll loop paused a fixed second before asking
for work again, so a checker took at most one batch of its slots per
second, whatever its machine could do. Under load, runs piled up in the
checker's queue and started late.

The loop now waits for the first freed slot, at most fullHeartbeat (5s),
so a checker whose slots stay busy still polls as a heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 14:15:48 +01:00
16 changed files with 710 additions and 81 deletions

No files matched your search

+1 -1
View File
@@ -152,7 +152,7 @@ helm install uptime uptimesebi/uptimesebi -n uptime --create-namespace \
--set ingress.enabled=true --set ingress.tls.enabled=true
```
The API pods serve metrics on port 9090 (`api.metrics`); `--set api.metrics.serviceMonitor.enabled=true` adds a ServiceMonitor for the Prometheus Operator. Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too.
The API pods serve metrics on port 9090 (`api.metrics`); `--set api.metrics.serviceMonitor.enabled=true` adds a ServiceMonitor for the Prometheus Operator, and `api.metrics.prometheusRule.enabled=true` alert rules for a region whose checks fall behind. Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too.
Run as many API, checker and status page instances as you need; they share no local state. The supported setups are:
@@ -0,0 +1,39 @@
{{- if and .Values.api.metrics.enabled .Values.api.metrics.prometheusRule.enabled }}
{{- $rule := .Values.api.metrics.prometheusRule }}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: {{ include "uptimesebi.fullname" . }}-api
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: api
{{- with $rule.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
groups:
- name: uptimesebi
rules:
# Every replica reports the same platform values, hence max().
- alert: UptimeSebiRegionBehind
expr: max by (region) (uptimesebi_checks_overdue) > 0
for: {{ $rule.regionBehindFor }}
labels:
severity: {{ $rule.severity }}
annotations:
summary: "Region {{ "{{ $labels.region }}" }} falls behind its checks"
description: >-
{{ "{{ $value }}" }} checks of region {{ "{{ $labels.region }}" }} are more than
10 seconds overdue: no checker of the region is live, or its
checkers cannot take the work in time.
- alert: UptimeSebiPlatformMetricsFailing
expr: max(uptimesebi_platform_metrics_error) > 0
for: 10m
labels:
severity: {{ $rule.severity }}
annotations:
summary: UptimeSebi cannot read its platform metrics
description: >-
The API fails to read the database or Redis for its platform
metrics, so UptimeSebiRegionBehind sees stale values.
{{- end }}
+11
View File
@@ -137,6 +137,17 @@ api:
interval: 30s
# Extra labels, for a Prometheus that selects ServiceMonitors by label.
labels: {}
# Alert rules for the Prometheus Operator: a region whose checks fall
# behind, and platform metrics that cannot be read. Needs the
# ServiceMonitor or another scrape of the metrics.
prometheusRule:
enabled: false
# How long checks must stay overdue before the alert fires.
regionBehindFor: 5m
severity: warning
# Extra labels, for a Prometheus that selects rules by label, like
# release: <name> with kube-prometheus-stack.
labels: {}
# The API image is built for amd64 only; checkers and status page servers
# run on arm64 and 32-bit ARM too. Also used by the migration job.
nodeSelector:
+19 -1
View File
@@ -227,7 +227,25 @@ func (s *Server) agentJobs(c *gin.Context) {
internalError(c, err)
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 {
internalError(c, err)
return
+3 -1
View File
@@ -85,7 +85,9 @@ func TestCheckerNetwork(t *testing.T) {
}
waitResult := func(id string, ok bool, what string) {
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)
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
})
+75 -28
View File
@@ -37,9 +37,15 @@ const (
// storeEvidence keeps the evidence of accepted results: per monitor and
// region the latest success, and failures unless an identical one was kept
// within failureEvidenceEvery. Evidence is an aid; failures are logged and
// never fail the report.
// within failureEvidenceEvery. All of a report's evidence is written in one
// 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) {
var (
successes = map[uuid.UUID]agentapi.Result{}
failures []agentapi.Result
failed []uuid.UUID
)
for _, r := range results {
m, ok := monitors[r.MonitorID]
if len(r.Evidence) == 0 || !ok {
@@ -49,34 +55,75 @@ 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))
continue
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if r.OK {
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil {
return err
}
} else {
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) {
return err
}
if r.OK {
// Only the latest success is kept anyway.
if prev, seen := successes[r.MonitorID]; !seen || r.StartedAt.After(prev.StartedAt) {
successes[r.MonitorID] = r
}
row := store.InsertEvidenceParams{
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
return q.InsertEvidence(ctx, row)
})
if err != nil {
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err)
continue
}
failures = append(failures, r)
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{
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
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 {
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 (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestEvidence(t *testing.T) {
@@ -103,3 +108,62 @@ func TestEvidence(t *testing.T) {
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)
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ var (
descCheckers = prometheus.NewDesc("uptimesebi_checker_instances",
"Live checker instances per platform region.", []string{"region"}, nil)
descOverdue = prometheus.NewDesc("uptimesebi_checks_overdue",
"Checks of a platform region due for more than 10 seconds, as when no checker of the region is live.", []string{"region"}, nil)
"Checks of a platform region due for more than 10 seconds and not started: undispatched, as when no checker of the region is live, or waiting in the queue of a checker too busy to take them.", []string{"region"}, nil)
descRegions = prometheus.NewDesc("uptimesebi_regions",
"Platform regions by whether a checker is live.", []string{"online"}, nil)
descOrgs = prometheus.NewDesc("uptimesebi_orgs",
+56 -6
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"log/slog"
"math/rand/v2"
"sync"
"sync/atomic"
"time"
@@ -30,6 +31,9 @@ const (
// quickPoll is a long poll answered empty faster than any wait would.
quickPoll = 200 * time.Millisecond
flushInterval = 2 * time.Second
// fullHeartbeat is how often a checker with every slot busy still polls,
// so the API keeps it live; well below schedule.StaleAfter.
fullHeartbeat = 5 * time.Second
// maxPending bounds results kept while the API is unreachable.
maxPending = 50_000
)
@@ -39,6 +43,8 @@ type Runner struct {
api API
log *slog.Logger
slots chan struct{}
// freed is signalled when a slot is freed, for a poll waiting for one.
freed chan struct{}
run func(context.Context, check.Spec) check.Outcome
results chan agentapi.Result
@@ -46,6 +52,8 @@ type Runner struct {
evidenceMu sync.Mutex
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.
@@ -61,13 +69,23 @@ const evidenceEvery = 10 * time.Minute
// shouldSendEvidence decides whether a result carries its evidence: every
// failure, every change between success and failure, and otherwise every
// 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 {
r.evidenceMu.Lock()
defer r.evidenceMu.Unlock()
last, seen := r.evidence[monitor]
send := !ok || !seen || last.ok != ok || now.Sub(last.sent) >= evidenceEvery
if send {
periodic := seen && last.ok == ok && now.Sub(last.sent) >= evidenceEvery
send := !ok || !seen || last.ok != ok || periodic
switch {
case periodic:
last.sent = now
case send:
last.sent = now.Add(-r.jitter(evidenceEvery))
}
last.ok = ok
r.evidence[monitor] = last
@@ -80,10 +98,12 @@ func New(api API, concurrency int, log *slog.Logger) *Runner {
api: api,
log: log,
slots: make(chan struct{}, max(concurrency, 1)),
freed: make(chan struct{}, 1),
run: check.Run,
results: make(chan agentapi.Result, 1024),
evidence: map[uuid.UUID]evidenceState{},
jitter: rand.N[time.Duration],
}
}
@@ -170,19 +190,49 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
r.slots <- struct{}{}
running.Add(1)
go func() {
defer func() { <-r.slots; running.Done() }()
defer func() { r.release(); running.Done() }()
r.results <- r.execute(ctx, j)
}()
}
// A long poll answered empty at once, as by an instance shutting
// down, is not repeated at once either.
if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) {
switch {
case free == 0:
// Take work again as soon as a check finishes, not after a
// fixed pause, which would cap throughput at slots per pause.
r.waitForSlot(ctx, fullHeartbeat)
case len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll:
// A long poll answered empty at once, as by an instance
// shutting down, is not repeated at once either.
sleep(ctx, time.Second)
}
}
return nil
}
// release frees a slot and wakes a poll waiting for one.
func (r *Runner) release() {
<-r.slots
select {
case r.freed <- struct{}{}:
default:
}
}
// waitForSlot returns once a slot is free, ctx is done or at most after
// d.
func (r *Runner) waitForSlot(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
for len(r.slots) == cap(r.slots) {
select {
case <-r.freed:
case <-ctx.Done():
return
case <-t.C:
return
}
}
}
func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
// Checks already started finish even during shutdown; their timeout
// bounds them.
+37
View File
@@ -10,6 +10,7 @@ import (
func TestEvidencePolicy(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler))
r.jitter = func(time.Duration) time.Duration { return 0 }
m := uuid.New()
now := time.Now()
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)
}
}
+108
View File
@@ -0,0 +1,108 @@
package checker
import (
"context"
"log/slog"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
)
// backlogAPI hands out queued jobs as fast as the checker asks for them.
type backlogAPI struct {
mu sync.Mutex
queued int
polls int
reported atomic.Int64
}
func (b *backlogAPI) Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) {
b.mu.Lock()
b.polls++
n := min(max, b.queued)
b.queued -= n
b.mu.Unlock()
if n == 0 {
select {
case <-time.After(min(wait, 50*time.Millisecond)):
case <-ctx.Done():
}
return nil, nil
}
jobs := make([]agentapi.Job, n)
for i := range jobs {
jobs[i] = agentapi.Job{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}
}
return jobs, nil
}
func (b *backlogAPI) Report(_ context.Context, rs []agentapi.Result) error {
b.reported.Add(int64(len(rs)))
return nil
}
func (b *backlogAPI) Release(context.Context) error { return nil }
// TestFullCheckerTakesWorkAsSlotsFree runs a backlog through a single slot.
// A checker pausing a second whenever its slots are full would need about a
// second per job.
func TestFullCheckerTakesWorkAsSlotsFree(t *testing.T) {
const jobs = 10
api := &backlogAPI{queued: jobs}
r := New(api, 1, slog.New(slog.DiscardHandler))
var ran atomic.Int64
r.run = func(context.Context, check.Spec) check.Outcome {
time.Sleep(5 * time.Millisecond)
ran.Add(1)
return check.Outcome{OK: true}
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- r.Run(ctx, time.Second) }()
start := time.Now()
for ran.Load() < jobs && time.Since(start) < 5*time.Second {
time.Sleep(5 * time.Millisecond)
}
took := time.Since(start)
cancel()
if err := <-done; err != nil {
t.Errorf("Run() = %v", err)
}
if n := ran.Load(); n != jobs {
t.Fatalf("ran %d checks in %v, want %d", n, took, jobs)
}
if took > 2*time.Second {
t.Errorf("%d checks through one slot took %v, want well under a second each", jobs, took)
}
if n := api.reported.Load(); n != jobs {
t.Errorf("reported %d results, want %d", n, jobs)
}
}
// TestWaitForSlotKeepsPolling bounds the wait, so a checker whose slots
// stay busy still polls as a heartbeat.
func TestWaitForSlotKeepsPolling(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler))
r.slots <- struct{}{}
start := time.Now()
r.waitForSlot(context.Background(), 50*time.Millisecond)
if took := time.Since(start); took < 50*time.Millisecond || took > time.Second {
t.Errorf("waitForSlot() with every slot busy returned after %v, want the bound of 50ms", took)
}
go func() {
time.Sleep(20 * time.Millisecond)
r.release()
}()
start = time.Now()
r.waitForSlot(context.Background(), 5*time.Second)
if took := time.Since(start); took > time.Second {
t.Errorf("waitForSlot() returned %v after a slot was freed, want at once", took)
}
}
+96 -16
View File
@@ -7,12 +7,18 @@
// number of API replicas can dispatch concurrently without a leader, and a
// lost job never stops a monitor from running again.
//
// Each monitor has a fixed phase within its interval, derived from its ID.
// After its first run, which is right away, a monitor runs on its phase, so
// runs spread evenly over the interval however the monitors were created,
// and late runs do not all gather at the moment they were dispatched.
//
// Instances announce themselves by polling. One that stops polling is
// considered gone after StaleAfter; its queued jobs return to the region.
package schedule
import (
"context"
"encoding/binary"
"errors"
"fmt"
"strconv"
@@ -33,6 +39,8 @@ const (
const (
keyRegions = "sched:regions"
keyIntervals = "sched:intervals"
// keyPhases holds each monitor's phase within its interval, in ms.
keyPhases = "sched:phases"
// keyTouched records when each monitor was last upserted, so a
// reconciliation based on an older database read leaves it alone.
keyTouched = "sched:touched"
@@ -69,20 +77,55 @@ type Monitor struct {
Regions []string
}
// phaseOf returns the phase of monitor id within interval, in ms. The ID's
// random bits spread the phases of all monitors evenly.
func phaseOf(id uuid.UUID, interval time.Duration) int64 {
ms := interval.Milliseconds()
if ms <= 0 {
return 0
}
return int64(binary.BigEndian.Uint64(id[8:]) % uint64(ms))
}
// nextSlot returns the first time after now, in ms, at which a monitor with
// phase and interval, both in ms, runs. dispatchScript computes the same.
func nextSlot(now, phase, interval int64) int64 {
if interval <= 0 {
return now
}
off := (now - phase) % interval
if off < 0 {
off += interval
}
return now - off + interval
}
// Upsert schedules m in its regions and removes it from others it was in.
// A monitor new to a region runs right away; an existing schedule keeps its
// phase so edits do not cause bursts.
// time so edits do not cause bursts.
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
return s.upsert(ctx, m, previousRegions, true)
}
// upsert is Upsert; without runNow, a monitor new to a region first runs on
// its phase instead of right away.
func (s *Scheduler) upsert(ctx context.Context, m Monitor, previousRegions []string, runNow bool) error {
now := s.now().UnixMilli()
id := m.ID.String()
phase := phaseOf(m.ID, m.Interval)
first := now
if !runNow {
first = nextSlot(now, phase, m.Interval.Milliseconds())
}
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
p.HSet(ctx, keyIntervals, id, m.Interval.Milliseconds())
p.HSet(ctx, keyPhases, id, phase)
p.HSet(ctx, keyTouched, id, now)
keep := map[string]bool{}
for _, r := range m.Regions {
keep[r] = true
p.SAdd(ctx, keyRegions, r)
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(first), Member: id})
}
for _, r := range previousRegions {
if !keep[r] {
@@ -99,6 +142,7 @@ func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []str
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HDel(ctx, keyIntervals, id.String())
p.HDel(ctx, keyPhases, id.String())
p.HDel(ctx, keyTouched, id.String())
for _, r := range regions {
p.ZRem(ctx, keyDue(r), id.String())
@@ -112,11 +156,12 @@ func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string)
// from the database at asOf. It repairs drift after a Redis failover or a
// missed update and is safe to run from several replicas. Monitors upserted
// after asOf are kept even if want lacks them: they were created while the
// database was being read.
// database was being read. Monitors it adds back first run on their phase,
// so recovering a lost schedule causes no burst.
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Time) error {
byRegion := map[string]map[string]bool{}
for _, m := range want {
if err := s.Upsert(ctx, m, nil); err != nil {
if err := s.upsert(ctx, m, nil, false); err != nil {
return err
}
for _, r := range m.Regions {
@@ -139,7 +184,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if wanted[id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -156,7 +201,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if byRegion[r][id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -168,7 +213,8 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
// upserted at or after asOf. Checking and removing in one step closes the
// window in which a concurrent upsert would be undone.
//
// KEYS: hash or sorted set to prune, touched hash. ARGV: monitor id, asOf ms.
// KEYS: hash or sorted set to prune, touched hash, phase hash.
// ARGV: monitor id, asOf ms.
var pruneScript = redis.NewScript(`
local touched = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
if touched >= tonumber(ARGV[2]) then return 0 end
@@ -177,6 +223,7 @@ if redis.call('TYPE', KEYS[1]).ok == 'zset' then
else
redis.call('HDEL', KEYS[1], ARGV[1])
redis.call('HDEL', KEYS[2], ARGV[1])
redis.call('HDEL', KEYS[3], ARGV[1])
end
return 1
`)
@@ -188,8 +235,14 @@ func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.
// dispatchScript runs per region.
//
// KEYS: due set, instance set, interval hash.
// KEYS: due set, instance set, interval hash, phase hash.
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
//
// The next run is the monitor's first phase slot after now. A run off its
// slot, like the first one, skips a slot less than half an interval away,
// so the monitor does not run twice in quick succession. Monitors without
// a phase, scheduled before phases existed, run every interval from their
// last due time until reconciliation adds one.
var dispatchScript = redis.NewScript(`
local now = tonumber(ARGV[1])
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
@@ -216,8 +269,17 @@ for i = 1, #due, 2 do
local q = ARGV[4] .. live[math.random(#live)]
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
redis.call('EXPIRE', q, ARGV[5])
local nxt = at + interval
if nxt <= now then nxt = now + interval end
local nxt
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
if phase == nil then
nxt = at + interval
if nxt <= now then nxt = now + interval end
else
nxt = now - ((now - phase) % interval) + interval
if (at - phase) % interval ~= 0 and nxt - now < interval / 2 then
nxt = nxt + interval
end
end
redis.call('ZADD', KEYS[1], nxt, m)
n = n + 1
end
@@ -236,7 +298,7 @@ func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
total := 0
for _, r := range regions {
n, err := dispatchScript.Run(ctx, s.rdb,
[]string{keyDue(r), keyInstances(r), keyIntervals},
[]string{keyDue(r), keyInstances(r), keyIntervals, keyPhases},
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
).Int()
if err != nil {
@@ -332,11 +394,29 @@ func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error)
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
}
// Overdue returns how many monitors of region should have been dispatched
// more than late ago, as when the region has no live instance.
// overdueScript counts the runs of a region due before a cutoff: those not
// dispatched yet and those waiting in an instance's queue.
//
// KEYS: due set, instance set.
// ARGV: cutoff ms, job queue prefix.
var overdueScript = redis.NewScript(`
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))
if at ~= nil and at <= cutoff then n = n + 1 end
end
end
return n
`)
// Overdue returns how many runs of region were due more than late ago and
// have not started: runs not dispatched, as when the region has no live
// instance, and runs left in the queue of an instance too busy to take them.
func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Duration) (int64, error) {
max := strconv.FormatInt(s.now().Add(-late).UnixMilli(), 10)
return s.rdb.ZCount(ctx, keyDue(region), "-inf", max).Result()
return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)},
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
}
func parseEntry(s string) (Entry, bool) {
+156 -4
View File
@@ -100,11 +100,20 @@ func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
*now = now.Add(30 * time.Second)
// The next run is on the monitor's phase, at least half an interval
// after the first one.
next := dueAt(t, s, "eu", m.ID)
if off := (next.UnixMilli() - phaseOf(m.ID, m.Interval)) % m.Interval.Milliseconds(); off != 0 {
t.Errorf("next run %v is %dms off its phase", next, off)
}
if gap := next.Sub(*now); gap < m.Interval/2 || gap > 3*m.Interval/2 {
t.Errorf("next run %v after the first, want between half and one and a half intervals", gap)
}
*now = next
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() after interval = %d, want 2", n)
t.Errorf("Dispatch() on the next slot = %d, want 2", n)
}
// Leaving a region stops runs there.
@@ -177,6 +186,9 @@ func TestRemoveAndReconcile(t *testing.T) {
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
if s.rdb.HExists(ctx, keyPhases, gone.ID.String()).Val() {
t.Error("Reconcile left the phase of a removed monitor")
}
}
func TestTakeWaits(t *testing.T) {
@@ -263,9 +275,149 @@ func TestOverdueCountsRunsLeftBehind(t *testing.T) {
if n := overdue(); n != 2 {
t.Errorf("Overdue() without instances = %d, want 2", n)
}
_ = s.Heartbeat(ctx, "eu", uuid.New())
busy := uuid.New()
_ = s.Heartbeat(ctx, "eu", busy)
mustDispatch(t, s)
// The queued runs were due 11 seconds ago and are still waiting.
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 {
t.Fatal(err)
}
if n := overdue(); n != 0 {
t.Errorf("Overdue() after dispatch = %d, want 0", n)
t.Errorf("Overdue() after the instance took the runs = %d, want 0", n)
}
}
func dueAt(t *testing.T, s *Scheduler, region string, id uuid.UUID) time.Time {
t.Helper()
score, err := s.rdb.ZScore(context.Background(), keyDue(region), id.String()).Result()
if err != nil {
t.Fatalf("no due time for %v in %s: %v", id, region, err)
}
return time.UnixMilli(int64(score))
}
// TestPhaseSpreadsBurst creates many monitors at once. Their first runs are
// right away; after that they spread over the interval instead of all
// running in the same second again.
func TestPhaseSpreadsBurst(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
perSecond := make([]int, 180)
for sec := range perSecond {
_ = s.Heartbeat(ctx, "eu", in)
perSecond[sec] = mustDispatch(t, s)
takeAll(t, s, in)
*now = now.Add(time.Second)
}
if perSecond[0] != monitors {
t.Errorf("first second dispatched %d, want all %d first runs", perSecond[0], monitors)
}
total, peak := 0, 0
for _, n := range perSecond[60:] {
total += n
peak = max(peak, n)
}
if total != 2*monitors {
t.Errorf("seconds 60 to 180 dispatched %d runs, want %d: one per monitor and minute", total, 2*monitors)
}
// 10 per second on average; all 600 at once without phases.
if peak > 30 {
t.Errorf("busiest second dispatched %d runs, want them spread at about 10 per second", peak)
}
}
// TestLateRunSnapsToPhase dispatches runs long overdue. Each comes back on
// its own phase instead of all gathering at the dispatch time.
func TestLateRunSnapsToPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
ms := []Monitor{}
for range 50 {
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
ms = append(ms, m)
_ = s.Upsert(ctx, m, nil)
}
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
// No instance for three intervals.
*now = now.Add(3*time.Minute + 7*time.Second)
_ = s.Heartbeat(ctx, "eu", in)
if n := mustDispatch(t, s); n != len(ms) {
t.Fatalf("Dispatch() of the overdue runs = %d, want %d", n, len(ms))
}
distinct := map[time.Time]bool{}
for _, m := range ms {
got := dueAt(t, s, "eu", m.ID)
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if !got.Equal(want) {
t.Errorf("monitor next due %v, want its next slot %v", got, want)
}
distinct[got] = true
}
if len(distinct) < len(ms)-5 {
t.Errorf("%d monitors share %d due times, want them apart", len(ms), len(distinct))
}
}
// TestReconcileAddsOnPhase rebuilds a lost schedule without a burst.
func TestReconcileAddsOnPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
ms := []Monitor{}
for range 20 {
ms = append(ms, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}})
}
if err := s.Reconcile(ctx, ms, *now); err != nil {
t.Fatal(err)
}
for _, m := range ms {
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if got := dueAt(t, s, "eu", m.ID); !got.Equal(want) {
t.Errorf("reconciled monitor due %v, want its slot %v", got, want)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() right after Reconcile = %d, want 0", n)
}
}
// TestPhaseFallback covers monitors scheduled before phases existed.
func TestPhaseFallback(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
s.rdb.HDel(ctx, keyPhases, m.ID.String())
mustDispatch(t, s)
if got, want := dueAt(t, s, "eu", m.ID), now.Add(time.Minute); !got.Equal(want) {
t.Errorf("monitor without phase next due %v, want one interval later, %v", got, want)
}
}
func TestNextSlot(t *testing.T) {
for _, c := range []struct{ now, phase, interval, want int64 }{
{now: 100, phase: 30, interval: 60, want: 150},
{now: 150, phase: 30, interval: 60, want: 210},
{now: 10, phase: 30, interval: 60, want: 30},
{now: 100, phase: 0, interval: 0, want: 100},
} {
if got := nextSlot(c.now, c.phase, c.interval); got != c.want {
t.Errorf("nextSlot(%d, %d, %d) = %d, want %d", c.now, c.phase, c.interval, got, c.want)
}
}
}
+34 -17
View File
@@ -13,17 +13,18 @@ import (
)
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 {
MonitorID uuid.UUID
Region string
Region string
MonitorIds []uuid.UUID
}
// Only the latest success per monitor and region is kept.
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
}
@@ -124,27 +125,43 @@ func (q *Queries) InsertEvidence(ctx context.Context, arg InsertEvidenceParams)
return err
}
const lastFailureEvidence = `-- name: LastFailureEvidence :one
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
WHERE monitor_id = $1 AND region = $2 AND NOT ok
ORDER BY time DESC LIMIT 1
const lastFailureEvidence = `-- name: LastFailureEvidence :many
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
FROM check_evidence
WHERE region = $1 AND NOT ok AND monitor_id = ANY($2::uuid[])
ORDER BY monitor_id, time DESC
`
type LastFailureEvidenceParams struct {
MonitorID uuid.UUID
Region string
Region string
MonitorIds []uuid.UUID
}
type LastFailureEvidenceRow struct {
Time time.Time
Error string
MonitorID uuid.UUID
Time time.Time
Error string
}
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) {
row := q.db.QueryRow(ctx, lastFailureEvidence, arg.MonitorID, arg.Region)
var i LastFailureEvidenceRow
err := row.Scan(&i.Time, &i.Error)
return i, err
// The newest failure per monitor in 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
if err := rows.Scan(&i.MonitorID, &i.Time, &i.Error); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listEvidence = `-- name: ListEvidence :many
+2 -1
View File
@@ -217,7 +217,8 @@ type Querier interface {
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, 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
// (see migration 00055) and has row-level security.
// 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
-- 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
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
WHERE monitor_id = $1 AND region = $2 AND NOT ok
ORDER BY time DESC LIMIT 1;
-- name: LastFailureEvidence :many
-- The newest failure per monitor in region.
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
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
-- Newest first, a page from a keyset cursor (see paging.go).