feat(store): record agent instances and query results by checker

Refs #82

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 12:54:56 +01:00
1 parent db8bdb3a62
commit 53ff2a628d
7 files changed
+289 -2

No files matched your search

@@ -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;
+130
View File
@@ -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
}
+81 -1
View File
@@ -12,6 +12,32 @@ import (
"github.com/google/uuid" "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 const dailyBuckets = `-- name: DailyBuckets :many
SELECT bucket::timestamptz AS bucket, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count SELECT bucket::timestamptz AS bucket, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count
FROM check_results_1d FROM check_results_1d
@@ -492,7 +518,7 @@ func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourly
} }
const recentResults = `-- name: RecentResults :many 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 FROM check_results
WHERE org_id = $1 AND monitor_id = $2 AND time > $3 WHERE org_id = $1 AND monitor_id = $2 AND time > $3
ORDER BY time DESC ORDER BY time DESC
@@ -512,6 +538,7 @@ type RecentResultsRow struct {
LatencyMs *int32 LatencyMs *int32
StatusCode *int32 StatusCode *int32
Error *string Error *string
CheckerID uuid.UUID
} }
func (q *Queries) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) { 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.LatencyMs,
&i.StatusCode, &i.StatusCode,
&i.Error, &i.Error,
&i.CheckerID,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -701,6 +729,58 @@ func (q *Queries) RegionBucketsHourly(ctx context.Context, arg RegionBucketsHour
return items, nil 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 const uptimeSince = `-- name: UptimeSince :many
SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count
FROM check_results_1h FROM check_results_1h
+9
View File
@@ -24,6 +24,15 @@ type Agent struct {
RegionID *uuid.UUID 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 { type AgentStorage struct {
Owner string Owner string
Key string Key string
+9
View File
@@ -17,8 +17,11 @@ type Querier interface {
AddMembership(ctx context.Context, arg AddMembershipParams) error AddMembership(ctx context.Context, arg AddMembershipParams) error
AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error
AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error
AgentInstancesByID(ctx context.Context, ids []uuid.UUID) ([]AgentInstancesByIDRow, error)
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error)
AnyUserExists(ctx context.Context) (bool, 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 // 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. // come back; SKIP LOCKED lets every API replica work the outbox.
ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) 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. // Moves the subgroups of a group that is about to be deleted.
ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error
ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, 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 ScrubAuditEmail(ctx context.Context, email string) error
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
// Changing the domain drops a previous verification. // Changing the domain drops a previous verification.
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) 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) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error)
// Deletes key and, as certmagic expects, everything below it. // Deletes key and, as certmagic expects, everything below it.
StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error) StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error)
@@ -233,6 +240,8 @@ type Querier interface {
StoragePut(ctx context.Context, arg StoragePutParams) error StoragePut(ctx context.Context, arg StoragePutParams) error
TouchAPIToken(ctx context.Context, id uuid.UUID) error TouchAPIToken(ctx context.Context, id uuid.UUID) error
TouchAgent(ctx context.Context, arg TouchAgentParams) 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 TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error) UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
@@ -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;
+16 -1
View File
@@ -13,7 +13,7 @@ WHERE org_id = $1 AND time > now() - interval '1 day'
ORDER BY monitor_id, region, time DESC; ORDER BY monitor_id, region, time DESC;
-- name: RecentResults :many -- 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 FROM check_results
WHERE org_id = $1 AND monitor_id = $2 AND time > $3 WHERE org_id = $1 AND monitor_id = $2 AND time > $3
ORDER BY time DESC ORDER BY time DESC
@@ -128,3 +128,18 @@ SELECT monitor_id, region, min(time)::timestamptz AS first
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $2 WHERE org_id = $1 AND time >= $2
GROUP BY 1, 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';