Files
uptimesebi/internal/api/agent.go
T
Sebastian UnterschützandClaude Opus 5.5 d4c8fd1d42 fix(api): store each reported check result once
A checker that lost the answer to a report, for example when its request
was cancelled while the API was still working, sent the batch again and
the API stored it twice, skewing statistics and counting failures twice
towards an incident. Results are now claimed in Redis by instance,
monitor and schedule time, and repeats are dropped. Found by CI, where
TestCheckersPerRegion saw a stopped checker's batch arrive twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 12:46:32 +01:00

331 lines
9.8 KiB
Go

package api
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// AgentTokenPrefix marks agent tokens, distinct from user API tokens.
const AgentTokenPrefix = "usa_"
const (
ctxAgent = "api.agent"
ctxInstance = "api.instance"
maxJobWait = 25 * time.Second
maxJobBatch = 200
)
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage)
sp.GET("/storage", s.storageGet)
sp.PUT("/storage", s.storagePut)
sp.DELETE("/storage", s.storageDelete)
sp.GET("/storage/stat", s.storageStat)
sp.GET("/storage/list", s.storageList)
sp.POST("/storage/lock", s.storageLock)
sp.DELETE("/storage/lock", s.storageUnlock)
checker := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults)
checker.POST("/release", s.agentRelease)
}
// agentAuth authenticates the agent token and the protocol version and
// requires an instance ID, which distinguishes processes sharing a token.
func (s *Server) agentAuth() gin.HandlerFunc {
return func(c *gin.Context) {
v, err := strconv.Atoi(c.GetHeader(agentapi.VersionHeader))
if err != nil || v < agentapi.Version-1 || v > agentapi.Version {
fail(c, http.StatusUpgradeRequired, "agent_protocol_unsupported")
return
}
instance, err := uuid.Parse(c.GetHeader(agentapi.InstanceHeader))
if err != nil {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
tok := bearerToken(c)
if len(tok) <= len(AgentTokenPrefix) || tok[:len(AgentTokenPrefix)] != AgentTokenPrefix {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
var a store.GetAgentByHashRow
release := truncate(c.GetHeader(agentapi.ReleaseHeader), 64)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil {
return err
}
return q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release})
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
if err != nil {
internalError(c, err)
return
}
c.Set(ctxAgent, a)
c.Set(ctxInstance, instance)
c.Next()
}
}
func requireAgentKind(kind string) gin.HandlerFunc {
return func(c *gin.Context) {
if agentOf(c).Kind != kind {
fail(c, http.StatusForbidden, "forbidden")
return
}
c.Next()
}
}
func agentOf(c *gin.Context) store.GetAgentByHashRow {
return c.MustGet(ctxAgent).(store.GetAgentByHashRow)
}
func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) }
// regionOf returns the agent's region ID in the string form used for the
// schedule and check results.
func regionOf(c *gin.Context) string {
if id := agentOf(c).RegionID; id != nil {
return id.String()
}
return ""
}
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
func (s *Server) allowPrivate(a store.GetAgentByHashRow) bool {
// Operator checkers in the cloud share our network; customers must not
// reach it through them. Customer-run checkers and self-hosted
// installations check whatever their operator can reach.
return !s.cloud() || a.OrgID != nil
}
func (s *Server) agentHello(c *gin.Context) {
a := agentOf(c)
c.JSON(http.StatusOK, agentapi.Hello{
AgentID: a.ID, Name: a.Name, Kind: a.Kind, Region: deref(a.RegionKey), RegionID: a.RegionID,
RegionName: deref(a.RegionName), OrgOwned: a.OrgID != nil, Protocol: agentapi.Version,
})
}
func (s *Server) agentJobs(c *gin.Context) {
var req agentapi.JobsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
region, instance := regionOf(c), instanceOf(c)
if err := s.sched.Heartbeat(ctx, region, instance); err != nil {
internalError(c, err)
return
}
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait)
if err != nil && ctx.Err() == nil {
internalError(c, err)
return
}
jobs, err := s.resolveJobs(ctx, agentOf(c), entries)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, agentapi.JobsResponse{Jobs: jobs})
}
// resolveJobs attaches the current monitor settings to dispatched runs.
// Checking is cross-tenant work, hence the system scope.
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, error) {
jobs := []agentapi.Job{}
if len(entries) == 0 {
return jobs, nil
}
ids := make([]uuid.UUID, len(entries))
for i, e := range entries {
ids[i] = e.MonitorID
}
var rows []store.Monitor
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
return err
})
if err != nil {
return nil, err
}
byID := make(map[uuid.UUID]store.Monitor, len(rows))
for _, m := range rows {
byID[m.ID] = m
}
for _, e := range entries {
m, ok := byID[e.MonitorID]
if !ok {
continue
}
jobs = append(jobs, agentapi.Job{
MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target,
TimeoutMS: int(m.TimeoutMs), Config: m.Config, AllowPrivate: s.allowPrivate(a),
})
}
return jobs, nil
}
func (s *Server) agentResults(c *gin.Context) {
var req agentapi.ResultsRequest
if !bind(c, &req) {
return
}
if len(req.Results) > agentapi.MaxResults {
fail(c, http.StatusRequestEntityTooLarge, "invalid_input")
return
}
ctx := c.Request.Context()
region, instance := regionOf(c), instanceOf(c)
fresh, seen, err := s.claimResults(ctx, instance, req.Results)
if err != nil {
internalError(c, err)
return
}
req.Results = fresh
ids := make([]uuid.UUID, len(req.Results))
for i, r := range req.Results {
ids[i] = r.MonitorID
}
now := time.Now()
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
var accepted []agentapi.Result
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
a := agentOf(c)
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
if err != nil {
return err
}
for _, m := range rows {
monitors[m.ID] = m
}
params := make([]store.InsertCheckResultsParams, 0, len(req.Results))
for _, r := range req.Results {
m, ok := monitors[r.MonitorID]
org := m.OrgID
// A checker may only report monitors of its own region, and
// timestamps far from now are rejected rather than skewing
// history.
if !ok || r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)) {
continue
}
row := store.InsertCheckResultsParams{
Time: r.StartedAt, OrgID: org, MonitorID: r.MonitorID, Region: region,
CheckerID: instance, Ok: r.OK, LatencyMs: ptr(int32(max(r.LatencyMS, 0))),
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
params = append(params, row)
accepted = append(accepted, r)
}
if len(params) == 0 {
return nil
}
_, err = q.InsertCheckResults(ctx, params)
return err
})
if err != nil {
// Unclaimed, the checker's retry is stored instead.
s.unclaimResults(context.WithoutCancel(ctx), seen)
internalError(c, err)
return
}
s.evaluateResults(ctx, region, accepted, monitors)
s.storeEvidence(ctx, region, instance, accepted, monitors)
c.Status(http.StatusNoContent)
}
func (s *Server) agentRelease(c *gin.Context) {
if err := s.sched.Release(c.Request.Context(), regionOf(c), instanceOf(c)); err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// truncateValid shortens s to n bytes without splitting a UTF-8 sequence.
func truncateValid(s string, n int) string {
if len(s) <= n {
return s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}
// resultClaimTTL covers the retries of a checker that lost the answer to a
// report, which happen within minutes.
const resultClaimTTL = 2 * time.Hour
// 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
// still working, sends the batch again; without this, the retry would be
// stored twice. A run is identified by instance, monitor and schedule time.
// It returns the new results and the claim keys to release if storing fails.
func (s *Server) claimResults(ctx context.Context, instance uuid.UUID, results []agentapi.Result) ([]agentapi.Result, []string, error) {
if len(results) == 0 {
return results, nil, nil
}
keys := make([]string, len(results))
cmds := make([]*redis.BoolCmd, len(results))
_, err := s.rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
for i, r := range results {
keys[i] = "result:" + instance.String() + ":" + r.MonitorID.String() + ":" + strconv.FormatInt(r.ScheduledAt.UnixMilli(), 10)
cmds[i] = p.SetNX(ctx, keys[i], 1, resultClaimTTL)
}
return nil
})
if err != nil {
return nil, nil, err
}
fresh := results[:0:0]
var claimed []string
for i, r := range results {
if cmds[i].Val() {
fresh = append(fresh, r)
claimed = append(claimed, keys[i])
}
}
return fresh, claimed, nil
}
func (s *Server) unclaimResults(ctx context.Context, keys []string) {
if len(keys) == 0 {
return
}
if err := s.rdb.Del(ctx, keys...).Err(); err != nil {
s.log.WarnContext(ctx, "releasing result claims failed", "error", err)
}
}