From 53ff2a628d584db253463f937f75c0034646f873 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 12:54:56 +0100 Subject: [PATCH] feat(store): record agent instances and query results by checker Refs #82 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .../migrations/sql/00032_agent_instances.sql | 24 ++++ internal/store/agent_instances.sql.go | 130 ++++++++++++++++++ internal/store/check_results.sql.go | 82 ++++++++++- internal/store/models.go | 9 ++ internal/store/querier.go | 9 ++ internal/store/queries/agent_instances.sql | 20 +++ internal/store/queries/check_results.sql | 17 ++- 7 files changed, 289 insertions(+), 2 deletions(-) create mode 100644 internal/migrations/sql/00032_agent_instances.sql create mode 100644 internal/store/agent_instances.sql.go create mode 100644 internal/store/queries/agent_instances.sql diff --git a/internal/migrations/sql/00032_agent_instances.sql b/internal/migrations/sql/00032_agent_instances.sql new file mode 100644 index 0000000..388024b --- /dev/null +++ b/internal/migrations/sql/00032_agent_instances.sql @@ -0,0 +1,24 @@ +-- +goose Up +-- Processes running with an agent token. Several may share a token; check +-- results name the instance that ran them. +CREATE TABLE agent_instances ( + id uuid PRIMARY KEY, + agent_id uuid NOT NULL REFERENCES agents (id) ON DELETE CASCADE, + org_id uuid REFERENCES orgs (id) ON DELETE CASCADE, + release text NOT NULL DEFAULT '', + started_at timestamptz NOT NULL DEFAULT now(), + last_seen_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX agent_instances_agent_idx ON agent_instances (agent_id, last_seen_at DESC); + +ALTER TABLE agent_instances ENABLE ROW LEVEL SECURITY; +ALTER TABLE agent_instances FORCE ROW LEVEL SECURITY; +-- Platform instances serve every organization and are visible to all, like +-- platform regions. +CREATE POLICY agent_instances_read ON agent_instances FOR SELECT + USING (app_scope_system() OR org_id IS NULL OR org_id = app_org_id()); +CREATE POLICY agent_instances_write ON agent_instances FOR ALL + USING (app_scope_system()) WITH CHECK (app_scope_system()); + +-- +goose Down +DROP TABLE agent_instances; diff --git a/internal/store/agent_instances.sql.go b/internal/store/agent_instances.sql.go new file mode 100644 index 0000000..ddcda64 --- /dev/null +++ b/internal/store/agent_instances.sql.go @@ -0,0 +1,130 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: agent_instances.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const agentInstancesByID = `-- name: AgentInstancesByID :many +SELECT i.id, i.agent_id, i.release, i.started_at, i.last_seen_at, i.org_id, + a.name AS agent_name, a.kind, r.id AS region_id, coalesce(r.name, '')::text AS region_name +FROM agent_instances i +JOIN agents a ON a.id = i.agent_id +LEFT JOIN regions r ON r.id = a.region_id +WHERE i.id = ANY ($1::uuid[]) +` + +type AgentInstancesByIDRow struct { + ID uuid.UUID + AgentID uuid.UUID + Release string + StartedAt time.Time + LastSeenAt time.Time + OrgID *uuid.UUID + AgentName string + Kind string + RegionID *uuid.UUID + RegionName string +} + +func (q *Queries) AgentInstancesByID(ctx context.Context, ids []uuid.UUID) ([]AgentInstancesByIDRow, error) { + rows, err := q.db.Query(ctx, agentInstancesByID, ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []AgentInstancesByIDRow{} + for rows.Next() { + var i AgentInstancesByIDRow + if err := rows.Scan( + &i.ID, + &i.AgentID, + &i.Release, + &i.StartedAt, + &i.LastSeenAt, + &i.OrgID, + &i.AgentName, + &i.Kind, + &i.RegionID, + &i.RegionName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const siblingInstances = `-- name: SiblingInstances :many +SELECT id, release, started_at, last_seen_at FROM agent_instances +WHERE agent_id = $1 AND last_seen_at > now() - interval '1 day' +ORDER BY last_seen_at DESC +` + +type SiblingInstancesRow struct { + ID uuid.UUID + Release string + StartedAt time.Time + LastSeenAt time.Time +} + +// Other instances of the same agent seen in the last day. +func (q *Queries) SiblingInstances(ctx context.Context, agentID uuid.UUID) ([]SiblingInstancesRow, error) { + rows, err := q.db.Query(ctx, siblingInstances, agentID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []SiblingInstancesRow{} + for rows.Next() { + var i SiblingInstancesRow + if err := rows.Scan( + &i.ID, + &i.Release, + &i.StartedAt, + &i.LastSeenAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const touchAgentInstance = `-- name: TouchAgentInstance :exec +INSERT INTO agent_instances (id, agent_id, org_id, release) +VALUES ($1, $2, $3, $4) +ON CONFLICT (id) DO UPDATE SET release = EXCLUDED.release, last_seen_at = now() +WHERE agent_instances.last_seen_at < now() - interval '1 minute' OR agent_instances.release <> EXCLUDED.release +` + +type TouchAgentInstanceParams struct { + ID uuid.UUID + AgentID uuid.UUID + OrgID *uuid.UUID + Release string +} + +// Writes at most once a minute per instance; agents poll far more often. +func (q *Queries) TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error { + _, err := q.db.Exec(ctx, touchAgentInstance, + arg.ID, + arg.AgentID, + arg.OrgID, + arg.Release, + ) + return err +} diff --git a/internal/store/check_results.sql.go b/internal/store/check_results.sql.go index 3ddd50e..64b726e 100644 --- a/internal/store/check_results.sql.go +++ b/internal/store/check_results.sql.go @@ -12,6 +12,32 @@ import ( "github.com/google/uuid" ) +const checkerStats = `-- name: CheckerStats :one +SELECT count(*)::bigint AS total, count(*) FILTER (WHERE NOT ok)::bigint AS failed, + coalesce(avg(latency_ms), 0)::real AS avg_latency_ms +FROM check_results +WHERE org_id = $1 AND checker_id = $2 AND time > now() - interval '1 hour' +` + +type CheckerStatsParams struct { + OrgID uuid.UUID + CheckerID uuid.UUID +} + +type CheckerStatsRow struct { + Total int64 + Failed int64 + AvgLatencyMs float32 +} + +// How much one instance checked for the organization in the last hour. +func (q *Queries) CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error) { + row := q.db.QueryRow(ctx, checkerStats, arg.OrgID, arg.CheckerID) + var i CheckerStatsRow + err := row.Scan(&i.Total, &i.Failed, &i.AvgLatencyMs) + return i, err +} + const dailyBuckets = `-- name: DailyBuckets :many SELECT bucket::timestamptz AS bucket, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count FROM check_results_1d @@ -492,7 +518,7 @@ func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourly } const recentResults = `-- name: RecentResults :many -SELECT time, region, ok, latency_ms, status_code, error +SELECT time, region, ok, latency_ms, status_code, error, checker_id FROM check_results WHERE org_id = $1 AND monitor_id = $2 AND time > $3 ORDER BY time DESC @@ -512,6 +538,7 @@ type RecentResultsRow struct { LatencyMs *int32 StatusCode *int32 Error *string + CheckerID uuid.UUID } func (q *Queries) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) { @@ -530,6 +557,7 @@ func (q *Queries) RecentResults(ctx context.Context, arg RecentResultsParams) ([ &i.LatencyMs, &i.StatusCode, &i.Error, + &i.CheckerID, ); err != nil { return nil, err } @@ -701,6 +729,58 @@ func (q *Queries) RegionBucketsHourly(ctx context.Context, arg RegionBucketsHour return items, nil } +const resultsByChecker = `-- name: ResultsByChecker :many +SELECT r.time, r.monitor_id, r.region, r.ok, r.latency_ms, r.status_code, r.error +FROM check_results r +WHERE r.org_id = $1 AND r.checker_id = $2 AND r.time > now() - interval '1 day' +ORDER BY r.time DESC +LIMIT 50 +` + +type ResultsByCheckerParams struct { + OrgID uuid.UUID + CheckerID uuid.UUID +} + +type ResultsByCheckerRow struct { + Time time.Time + MonitorID uuid.UUID + Region string + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +// The organization's latest results run by one checker instance. +func (q *Queries) ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error) { + rows, err := q.db.Query(ctx, resultsByChecker, arg.OrgID, arg.CheckerID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ResultsByCheckerRow{} + for rows.Next() { + var i ResultsByCheckerRow + if err := rows.Scan( + &i.Time, + &i.MonitorID, + &i.Region, + &i.Ok, + &i.LatencyMs, + &i.StatusCode, + &i.Error, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const uptimeSince = `-- name: UptimeSince :many SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count FROM check_results_1h diff --git a/internal/store/models.go b/internal/store/models.go index 6e27c11..b027dbb 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -24,6 +24,15 @@ type Agent struct { RegionID *uuid.UUID } +type AgentInstance struct { + ID uuid.UUID + AgentID uuid.UUID + OrgID *uuid.UUID + Release string + StartedAt time.Time + LastSeenAt time.Time +} + type AgentStorage struct { Owner string Key string diff --git a/internal/store/querier.go b/internal/store/querier.go index 68f1a5e..655fdeb 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -17,8 +17,11 @@ type Querier interface { AddMembership(ctx context.Context, arg AddMembershipParams) error AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error + AgentInstancesByID(ctx context.Context, ids []uuid.UUID) ([]AgentInstancesByIDRow, error) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AnyUserExists(ctx context.Context) (bool, error) + // How much one instance checked for the organization in the last hour. + CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error) // System scope. Leases due rows for five minutes so a crashed sender's rows // come back; SKIP LOCKED lets every API replica work the outbox. ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) @@ -219,12 +222,16 @@ type Querier interface { // Moves the subgroups of a group that is about to be deleted. ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) + // The organization's latest results run by one checker instance. + ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error) ScrubAuditEmail(ctx context.Context, email string) error SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error // Changing the domain drops a previous verification. SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error + // Other instances of the same agent seen in the last day. + SiblingInstances(ctx context.Context, agentID uuid.UUID) ([]SiblingInstancesRow, error) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) // Deletes key and, as certmagic expects, everything below it. StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error) @@ -233,6 +240,8 @@ type Querier interface { StoragePut(ctx context.Context, arg StoragePutParams) error TouchAPIToken(ctx context.Context, id uuid.UUID) error TouchAgent(ctx context.Context, arg TouchAgentParams) error + // Writes at most once a minute per instance; agents poll far more often. + TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error) diff --git a/internal/store/queries/agent_instances.sql b/internal/store/queries/agent_instances.sql new file mode 100644 index 0000000..63e3f76 --- /dev/null +++ b/internal/store/queries/agent_instances.sql @@ -0,0 +1,20 @@ +-- name: TouchAgentInstance :exec +-- Writes at most once a minute per instance; agents poll far more often. +INSERT INTO agent_instances (id, agent_id, org_id, release) +VALUES ($1, $2, $3, $4) +ON CONFLICT (id) DO UPDATE SET release = EXCLUDED.release, last_seen_at = now() +WHERE agent_instances.last_seen_at < now() - interval '1 minute' OR agent_instances.release <> EXCLUDED.release; + +-- name: AgentInstancesByID :many +SELECT i.id, i.agent_id, i.release, i.started_at, i.last_seen_at, i.org_id, + a.name AS agent_name, a.kind, r.id AS region_id, coalesce(r.name, '')::text AS region_name +FROM agent_instances i +JOIN agents a ON a.id = i.agent_id +LEFT JOIN regions r ON r.id = a.region_id +WHERE i.id = ANY (sqlc.arg(ids)::uuid[]); + +-- name: SiblingInstances :many +-- Other instances of the same agent seen in the last day. +SELECT id, release, started_at, last_seen_at FROM agent_instances +WHERE agent_id = $1 AND last_seen_at > now() - interval '1 day' +ORDER BY last_seen_at DESC; diff --git a/internal/store/queries/check_results.sql b/internal/store/queries/check_results.sql index e4b49e5..14c6a1b 100644 --- a/internal/store/queries/check_results.sql +++ b/internal/store/queries/check_results.sql @@ -13,7 +13,7 @@ WHERE org_id = $1 AND time > now() - interval '1 day' ORDER BY monitor_id, region, time DESC; -- name: RecentResults :many -SELECT time, region, ok, latency_ms, status_code, error +SELECT time, region, ok, latency_ms, status_code, error, checker_id FROM check_results WHERE org_id = $1 AND monitor_id = $2 AND time > $3 ORDER BY time DESC @@ -128,3 +128,18 @@ SELECT monitor_id, region, min(time)::timestamptz AS first FROM check_results WHERE org_id = $1 AND time >= $2 GROUP BY 1, 2; + +-- name: ResultsByChecker :many +-- The organization's latest results run by one checker instance. +SELECT r.time, r.monitor_id, r.region, r.ok, r.latency_ms, r.status_code, r.error +FROM check_results r +WHERE r.org_id = $1 AND r.checker_id = sqlc.arg(checker_id) AND r.time > now() - interval '1 day' +ORDER BY r.time DESC +LIMIT 50; + +-- name: CheckerStats :one +-- How much one instance checked for the organization in the last hour. +SELECT count(*)::bigint AS total, count(*) FILTER (WHERE NOT ok)::bigint AS failed, + coalesce(avg(latency_ms), 0)::real AS avg_latency_ms +FROM check_results +WHERE org_id = $1 AND checker_id = sqlc.arg(checker_id) AND time > now() - interval '1 hour';