package api import ( "context" "encoding/json" "slices" "time" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" ) // regionKey identifies a monitor in one region. type regionKey struct { monitor uuid.UUID region string } // latestRow is a result as UpsertLatestResults reads it. type latestRow struct { MonitorID uuid.UUID `json:"monitor_id"` Region string `json:"region"` OrgID uuid.UUID `json:"org_id"` Time time.Time `json:"time"` OK bool `json:"ok"` LatencyMS *int32 `json:"latency_ms"` StatusCode *int32 `json:"status_code"` Error *string `json:"error"` } // insertResults stores results and keeps the newest per monitor and // region in latest_results, which the console reads instead of a day of // results. It returns the organizations whose status changed somewhere, // for pagesChanged once the transaction is committed. func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) ([]uuid.UUID, error) { if _, err := q.InsertCheckResults(ctx, rows); err != nil { return nil, err } latest := make([]latestRow, len(rows)) for i, r := range rows { latest[i] = latestRow{ MonitorID: r.MonitorID, Region: r.Region, OrgID: r.OrgID, Time: r.Time, OK: r.Ok, LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error, } } b, err := json.Marshal(latest) if err != nil { return nil, err } ids := make([]uuid.UUID, len(rows)) for i, r := range rows { ids[i] = r.MonitorID } before, err := q.LatestOK(ctx, ids) if err != nil { return nil, err } was := make(map[regionKey]bool, len(before)) for _, r := range before { was[regionKey{r.MonitorID, r.Region}] = r.Ok } written, err := q.UpsertLatestResults(ctx, b) if err != nil { return nil, err } var changed []uuid.UUID for _, w := range written { if ok, seen := was[regionKey{w.MonitorID, w.Region}]; (!seen || ok != w.Ok) && !slices.Contains(changed, w.OrgID) { changed = append(changed, w.OrgID) } } return changed, nil }