diff --git a/internal/api/agent.go b/internal/api/agent.go index be0079c..3eff643 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -11,6 +11,7 @@ import ( "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" @@ -202,6 +203,12 @@ func (s *Server) agentResults(c *gin.Context) { } 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 @@ -209,7 +216,7 @@ func (s *Server) agentResults(c *gin.Context) { 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 { + 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 { @@ -248,6 +255,8 @@ func (s *Server) agentResults(c *gin.Context) { return err }) if err != nil { + // Unclaimed, the checker's retry is stored instead. + s.unclaimResults(context.WithoutCancel(ctx), seen) internalError(c, err) return } @@ -274,3 +283,48 @@ func truncateValid(s string, n int) string { } 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) + } +} diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go index 9bbedf5..b0d2173 100644 --- a/internal/api/checker_test.go +++ b/internal/api/checker_test.go @@ -207,3 +207,38 @@ func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { time.Sleep(100 * time.Millisecond) } } + +// A checker that lost the answer to a report sends it again; the results +// must not be stored twice. +func TestResultReportIsIdempotent(t *testing.T) { + e := newEnv(t) + tok, region := e.platformChecker(t, uniq("eu-")) + owner := e.browser(t) + owner.signup("o@"+uniq("id")+".test", uniq("id-")) + _, 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}, + }) + monitor := uuid.MustParse(m["id"].(string)) + client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) + at := time.Now().Truncate(time.Millisecond) + batch := []agentapi.Result{ + {MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true}, + {MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false}, + } + for range 3 { + if err := client.Report(context.Background(), batch); err != nil { + t.Fatal(err) + } + } + if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 { + t.Errorf("stored results = %d, want 2", n) + } + // Another instance's run of the same schedule time is its own result. + other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) + if err := other.Report(context.Background(), batch[:1]); err != nil { + t.Fatal(err) + } + if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 { + t.Errorf("stored results = %d, want 3", n) + } +}