diff --git a/internal/migrations/sql/00013_monitors.sql b/internal/migrations/sql/00013_monitors.sql new file mode 100644 index 0000000..7bdcc26 --- /dev/null +++ b/internal/migrations/sql/00013_monitors.sql @@ -0,0 +1,115 @@ +-- +goose Up +-- Regions appear when a checker for them first starts. Organization-private +-- regions for customer-hosted checkers follow with the remote mode. +CREATE TABLE regions ( + key text PRIMARY KEY CHECK (key ~ '^[a-z0-9][a-z0-9-]{0,39}$'), + name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE monitors ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200), + type text NOT NULL CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls')), + target text NOT NULL CHECK (length(target) BETWEEN 1 AND 2000), + interval_seconds integer NOT NULL CHECK (interval_seconds BETWEEN 10 AND 86400), + timeout_ms integer NOT NULL CHECK (timeout_ms BETWEEN 100 AND 60000), + -- Type-specific settings, validated by the application. + config jsonb NOT NULL DEFAULT '{}', + enabled boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX monitors_org_idx ON monitors (org_id); + +CREATE TABLE monitor_regions ( + monitor_id uuid NOT NULL REFERENCES monitors (id) ON DELETE CASCADE, + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + region text NOT NULL REFERENCES regions (key), + PRIMARY KEY (monitor_id, region) +); + +ALTER TABLE monitors ENABLE ROW LEVEL SECURITY; +ALTER TABLE monitors FORCE ROW LEVEL SECURITY; +CREATE POLICY monitors_tenant ON monitors FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +ALTER TABLE monitor_regions ENABLE ROW LEVEL SECURITY; +ALTER TABLE monitor_regions FORCE ROW LEVEL SECURITY; +CREATE POLICY monitor_regions_tenant ON monitor_regions FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- check_results is deliberately not under row-level security: TimescaleDB +-- refuses both compression and continuous aggregates on tables with row +-- security. Tenant isolation for this table and its aggregates is enforced +-- in the queries, which all take org_id as a parameter. +CREATE TABLE check_results ( + time timestamptz NOT NULL, + org_id uuid NOT NULL, + monitor_id uuid NOT NULL, + region text NOT NULL, + checker_id uuid NOT NULL, + ok boolean NOT NULL, + latency_ms integer, + status_code integer, + error text +); + +SELECT create_hypertable('check_results', by_range('time', INTERVAL '1 day')); +CREATE INDEX check_results_monitor_idx ON check_results (monitor_id, time DESC); + +ALTER TABLE check_results SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'org_id, monitor_id, region', + timescaledb.compress_orderby = 'time DESC' +); +SELECT add_compression_policy('check_results', INTERVAL '7 days'); +SELECT add_retention_policy('check_results', INTERVAL '90 days'); + +CREATE MATERIALIZED VIEW check_results_1h WITH (timescaledb.continuous) AS +SELECT time_bucket(INTERVAL '1 hour', time) AS bucket, + org_id, monitor_id, region, + count(*) AS total, + count(*) FILTER (WHERE ok) AS ok_count, + avg(latency_ms)::real AS avg_latency_ms, + max(latency_ms) AS max_latency_ms +FROM check_results +GROUP BY 1, 2, 3, 4 +WITH NO DATA; + +-- Include the not yet materialized recent hours in queries. +ALTER MATERIALIZED VIEW check_results_1h SET (timescaledb.materialized_only = false); + +SELECT add_continuous_aggregate_policy('check_results_1h', + start_offset => INTERVAL '3 days', end_offset => INTERVAL '5 minutes', schedule_interval => INTERVAL '5 minutes'); + +CREATE MATERIALIZED VIEW check_results_1d WITH (timescaledb.continuous) AS +SELECT time_bucket(INTERVAL '1 day', bucket) AS bucket, + org_id, monitor_id, region, + sum(total)::bigint AS total, + sum(ok_count)::bigint AS ok_count, + (sum(avg_latency_ms * total) / nullif(sum(total), 0))::real AS avg_latency_ms, + max(max_latency_ms) AS max_latency_ms +FROM check_results_1h +GROUP BY 1, 2, 3, 4 +WITH NO DATA; + +ALTER MATERIALIZED VIEW check_results_1d SET (timescaledb.materialized_only = false); + +SELECT add_continuous_aggregate_policy('check_results_1d', + start_offset => INTERVAL '30 days', end_offset => INTERVAL '1 hour', schedule_interval => INTERVAL '1 hour'); + +-- Aggregates outlive the raw data. +SELECT add_retention_policy('check_results_1h', INTERVAL '400 days'); + +-- +goose Down +DROP MATERIALIZED VIEW check_results_1d; +DROP MATERIALIZED VIEW check_results_1h; +DROP TABLE check_results; +DROP TABLE monitor_regions; +DROP TABLE monitors; +DROP TABLE regions; diff --git a/internal/migrations/sql/00014_agents.sql b/internal/migrations/sql/00014_agents.sql new file mode 100644 index 0000000..f5d4f7f --- /dev/null +++ b/internal/migrations/sql/00014_agents.sql @@ -0,0 +1,28 @@ +-- +goose Up +-- Agents are checkers and status page servers. Agents without an org are run +-- by the operator and serve every organization; org-owned agents arrive with +-- customer-hosted checkers. +CREATE TABLE agents ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs (id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('checker', 'statuspage')), + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + region text REFERENCES regions (key), + token_hash bytea NOT NULL UNIQUE, + prefix text NOT NULL, + last_seen_at timestamptz, + release text, + created_at timestamptz NOT NULL DEFAULT now(), + CHECK ((kind = 'checker') = (region IS NOT NULL)) +); + +ALTER TABLE agents ENABLE ROW LEVEL SECURITY; +ALTER TABLE agents FORCE ROW LEVEL SECURITY; +CREATE POLICY agents_read ON agents FOR SELECT + USING (org_id IS NULL OR app_scope_system() OR org_id = app_org_id()); +CREATE POLICY agents_write ON agents FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +DROP TABLE agents; diff --git a/internal/store/agents.sql.go b/internal/store/agents.sql.go new file mode 100644 index 0000000..c2fd43a --- /dev/null +++ b/internal/store/agents.sql.go @@ -0,0 +1,179 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: agents.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const createAgent = `-- name: CreateAgent :one +INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at +` + +type CreateAgentParams struct { + OrgID *uuid.UUID + Kind string + Name string + Region *string + TokenHash []byte + Prefix string +} + +func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) { + row := q.db.QueryRow(ctx, createAgent, + arg.OrgID, + arg.Kind, + arg.Name, + arg.Region, + arg.TokenHash, + arg.Prefix, + ) + var i Agent + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ) + return i, err +} + +const deleteAgent = `-- name: DeleteAgent :execrows +DELETE FROM agents WHERE id = $1 +` + +func (q *Queries) DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteAgent, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAgentByHash = `-- name: GetAgentByHash :one +SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents WHERE token_hash = $1 +` + +func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) { + row := q.db.QueryRow(ctx, getAgentByHash, tokenHash) + var i Agent + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ) + return i, err +} + +const listAgents = `-- name: ListAgents :many +SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents ORDER BY kind, region, name +` + +func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) { + rows, err := q.db.Query(ctx, listAgents) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Agent{} + for rows.Next() { + var i Agent + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listRegions = `-- name: ListRegions :many +SELECT key, name, created_at FROM regions ORDER BY key +` + +func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) { + rows, err := q.db.Query(ctx, listRegions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Region{} + for rows.Next() { + var i Region + if err := rows.Scan(&i.Key, &i.Name, &i.CreatedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const touchAgent = `-- name: TouchAgent :exec +UPDATE agents SET last_seen_at = now(), release = $2 +WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 seconds' OR release IS DISTINCT FROM $2) +` + +type TouchAgentParams struct { + ID uuid.UUID + Release *string +} + +func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error { + _, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release) + return err +} + +const upsertRegion = `-- name: UpsertRegion :one +INSERT INTO regions (key, name) VALUES ($1, coalesce(nullif($2::text, ''), $1)) +ON CONFLICT (key) DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING key, name, created_at +` + +type UpsertRegionParams struct { + Key string + Name string +} + +// An empty name names a new region after its key and keeps an existing name. +func (q *Queries) UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) { + row := q.db.QueryRow(ctx, upsertRegion, arg.Key, arg.Name) + var i Region + err := row.Scan(&i.Key, &i.Name, &i.CreatedAt) + return i, err +} diff --git a/internal/store/check_results.sql.go b/internal/store/check_results.sql.go new file mode 100644 index 0000000..ffceffb --- /dev/null +++ b/internal/store/check_results.sql.go @@ -0,0 +1,161 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: check_results.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +type InsertCheckResultsParams struct { + Time time.Time + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + CheckerID uuid.UUID + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +const latestResults = `-- name: LatestResults :many +SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND time > now() - interval '1 day' +ORDER BY monitor_id, region, time DESC +` + +type LatestResultsRow struct { + MonitorID uuid.UUID + Region string + Time time.Time + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +// Newest result per monitor and region in the org. +func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) { + rows, err := q.db.Query(ctx, latestResults, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []LatestResultsRow{} + for rows.Next() { + var i LatestResultsRow + if err := rows.Scan( + &i.MonitorID, + &i.Region, + &i.Time, + &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 recentResults = `-- name: RecentResults :many +SELECT time, region, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > $3 +ORDER BY time DESC +LIMIT 500 +` + +type RecentResultsParams struct { + OrgID uuid.UUID + MonitorID uuid.UUID + Time time.Time +} + +type RecentResultsRow struct { + Time time.Time + Region string + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +func (q *Queries) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) { + rows, err := q.db.Query(ctx, recentResults, arg.OrgID, arg.MonitorID, arg.Time) + if err != nil { + return nil, err + } + defer rows.Close() + items := []RecentResultsRow{} + for rows.Next() { + var i RecentResultsRow + if err := rows.Scan( + &i.Time, + &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 +WHERE org_id = $1 AND bucket >= $2 +GROUP BY monitor_id +` + +type UptimeSinceParams struct { + OrgID uuid.UUID + Bucket interface{} +} + +type UptimeSinceRow struct { + MonitorID uuid.UUID + Total int64 + OkCount int64 +} + +// Uptime per monitor from the hourly aggregate, including the not yet +// materialized most recent hours (real-time aggregation). +func (q *Queries) UptimeSince(ctx context.Context, arg UptimeSinceParams) ([]UptimeSinceRow, error) { + rows, err := q.db.Query(ctx, uptimeSince, arg.OrgID, arg.Bucket) + if err != nil { + return nil, err + } + defer rows.Close() + items := []UptimeSinceRow{} + for rows.Next() { + var i UptimeSinceRow + if err := rows.Scan(&i.MonitorID, &i.Total, &i.OkCount); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/store/copyfrom.go b/internal/store/copyfrom.go index d60d6fd..bf2d682 100644 --- a/internal/store/copyfrom.go +++ b/internal/store/copyfrom.go @@ -9,6 +9,48 @@ import ( "context" ) +// iteratorForInsertCheckResults implements pgx.CopyFromSource. +type iteratorForInsertCheckResults struct { + rows []InsertCheckResultsParams + skippedFirstNextCall bool +} + +func (r *iteratorForInsertCheckResults) Next() bool { + if len(r.rows) == 0 { + return false + } + if !r.skippedFirstNextCall { + r.skippedFirstNextCall = true + return true + } + r.rows = r.rows[1:] + return len(r.rows) > 0 +} + +func (r iteratorForInsertCheckResults) Values() ([]interface{}, error) { + return []interface{}{ + r.rows[0].Time, + r.rows[0].OrgID, + r.rows[0].MonitorID, + r.rows[0].Region, + r.rows[0].CheckerID, + r.rows[0].Ok, + r.rows[0].LatencyMs, + r.rows[0].StatusCode, + r.rows[0].Error, + }, nil +} + +func (r iteratorForInsertCheckResults) Err() error { + return nil +} + +// check_results and its aggregates have no row-level security (see +// migration 00013). Every query here must filter by org_id. +func (q *Queries) InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error) { + return q.db.CopyFrom(ctx, []string{"check_results"}, []string{"time", "org_id", "monitor_id", "region", "checker_id", "ok", "latency_ms", "status_code", "error"}, &iteratorForInsertCheckResults{rows: arg}) +} + // iteratorForInsertRecoveryCodes implements pgx.CopyFromSource. type iteratorForInsertRecoveryCodes struct { rows []InsertRecoveryCodesParams diff --git a/internal/store/models.go b/internal/store/models.go index 1afa83b..23c7587 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -10,6 +10,19 @@ import ( "github.com/google/uuid" ) +type Agent struct { + ID uuid.UUID + OrgID *uuid.UUID + Kind string + Name string + Region *string + TokenHash []byte + Prefix string + LastSeenAt *time.Time + Release *string + CreatedAt time.Time +} + type ApiToken struct { ID uuid.UUID OrgID uuid.UUID @@ -23,6 +36,40 @@ type ApiToken struct { CreatedAt time.Time } +type CheckResult struct { + Time time.Time + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + CheckerID uuid.UUID + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +type CheckResults1d struct { + Bucket interface{} + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + Total int64 + OkCount int64 + AvgLatencyMs float32 + MaxLatencyMs interface{} +} + +type CheckResults1h struct { + Bucket interface{} + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + Total int64 + OkCount int64 + AvgLatencyMs float32 + MaxLatencyMs interface{} +} + type Invitation struct { ID uuid.UUID OrgID uuid.UUID @@ -42,6 +89,26 @@ type Membership struct { CreatedAt time.Time } +type Monitor struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + +type MonitorRegion struct { + MonitorID uuid.UUID + OrgID uuid.UUID + Region string +} + type Org struct { ID uuid.UUID Slug string @@ -60,6 +127,12 @@ type RecoveryCode struct { CreatedAt time.Time } +type Region struct { + Key string + Name string + CreatedAt time.Time +} + type Role struct { ID uuid.UUID OrgID *uuid.UUID diff --git a/internal/store/monitors.sql.go b/internal/store/monitors.sql.go new file mode 100644 index 0000000..6161932 --- /dev/null +++ b/internal/store/monitors.sql.go @@ -0,0 +1,332 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: monitors.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const addMonitorRegion = `-- name: AddMonitorRegion :exec +INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3) +` + +type AddMonitorRegionParams struct { + MonitorID uuid.UUID + OrgID uuid.UUID + Region string +} + +func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error { + _, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.Region) + return err +} + +const allMonitorRegions = `-- name: AllMonitorRegions :many +SELECT monitor_id, region FROM monitor_regions +` + +type AllMonitorRegionsRow struct { + MonitorID uuid.UUID + Region string +} + +func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) { + rows, err := q.db.Query(ctx, allMonitorRegions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []AllMonitorRegionsRow{} + for rows.Next() { + var i AllMonitorRegionsRow + if err := rows.Scan(&i.MonitorID, &i.Region); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const createMonitor = `-- name: CreateMonitor :one +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +` + +type CreateMonitorParams struct { + OrgID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool +} + +func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) { + row := q.db.QueryRow(ctx, createMonitor, + arg.OrgID, + arg.Name, + arg.Type, + arg.Target, + arg.IntervalSeconds, + arg.TimeoutMs, + arg.Config, + arg.Enabled, + ) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteMonitor = `-- name: DeleteMonitor :execrows +DELETE FROM monitors WHERE id = $1 +` + +func (q *Queries) DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteMonitor, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteMonitorRegions = `-- name: DeleteMonitorRegions :exec +DELETE FROM monitor_regions WHERE monitor_id = $1 +` + +func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error { + _, err := q.db.Exec(ctx, deleteMonitorRegions, monitorID) + return err +} + +const getMonitor = `-- name: GetMonitor :one +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors WHERE id = $1 +` + +func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) { + row := q.db.QueryRow(ctx, getMonitor, id) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const listEnabledMonitorsForSchedule = `-- name: ListEnabledMonitorsForSchedule :many +SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id +WHERE m.enabled +GROUP BY m.id, m.interval_seconds +` + +type ListEnabledMonitorsForScheduleRow struct { + ID uuid.UUID + IntervalSeconds int32 + Regions []string +} + +// System scope: every enabled monitor with its regions, for reconciling the +// schedule. +func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) { + rows, err := q.db.Query(ctx, listEnabledMonitorsForSchedule) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListEnabledMonitorsForScheduleRow{} + for rows.Next() { + var i ListEnabledMonitorsForScheduleRow + if err := rows.Scan(&i.ID, &i.IntervalSeconds, &i.Regions); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMonitors = `-- name: ListMonitors :many +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors ORDER BY name +` + +func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { + rows, err := q.db.Query(ctx, listMonitors) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Monitor{} + for rows.Next() { + var i Monitor + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const monitorRegions = `-- name: MonitorRegions :many +SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region +` + +func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) { + rows, err := q.db.Query(ctx, monitorRegions, monitorID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []string{} + for rows.Next() { + var region string + if err := rows.Scan(®ion); err != nil { + return nil, err + } + items = append(items, region) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const monitorsForJobs = `-- name: MonitorsForJobs :many +SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 +WHERE m.id = ANY ($2::uuid[]) AND m.enabled +` + +type MonitorsForJobsParams struct { + Region string + Ids []uuid.UUID +} + +// System scope: monitors to hand to a checker of region, skipping ones that +// were disabled, deleted or moved out of the region since dispatch. +func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) { + rows, err := q.db.Query(ctx, monitorsForJobs, arg.Region, arg.Ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Monitor{} + for rows.Next() { + var i Monitor + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const updateMonitor = `-- name: UpdateMonitor :one +UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, + timeout_ms = $6, config = $7, enabled = $8, updated_at = now() +WHERE id = $1 +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +` + +type UpdateMonitorParams struct { + ID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool +} + +func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) { + row := q.db.QueryRow(ctx, updateMonitor, + arg.ID, + arg.Name, + arg.Type, + arg.Target, + arg.IntervalSeconds, + arg.TimeoutMs, + arg.Config, + arg.Enabled, + ) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/querier.go b/internal/store/querier.go index b88cd25..e885093 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -13,22 +13,29 @@ import ( type Querier interface { APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error) AddMembership(ctx context.Context, arg AddMembershipParams) error + AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error + AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AnyUserExists(ctx context.Context) (bool, error) // Shortens tokens that would outlive a newly set maximum lifetime. ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) + CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) + CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) + DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) + DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error) + DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) @@ -38,26 +45,39 @@ type Querier interface { EnableTOTP(ctx context.Context, arg EnableTOTPParams) error GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) + GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error) GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) + GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) GetRole(ctx context.Context, id uuid.UUID) (Role, error) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error) + // check_results and its aggregates have no row-level security (see + // migration 00013). Every query here must filter by org_id. + InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) + // Newest result per monitor and region in the org. + LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) + ListAgents(ctx context.Context) ([]Agent, error) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) + // System scope: every enabled monitor with its regions, for reconciling the + // schedule. + ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) + ListMonitors(ctx context.Context) ([]Monitor, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) + ListRegions(ctx context.Context) ([]Region, error) ListRoles(ctx context.Context) ([]Role, error) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) @@ -65,15 +85,27 @@ type Querier interface { MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) // Every role a member holds, with the scope it applies to. MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) + MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) + // System scope: monitors to hand to a checker of region, skipping ones that + // were disabled, deleted or moved out of the region since dispatch. + MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) + RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error TouchAPIToken(ctx context.Context, id uuid.UUID) error + TouchAgent(ctx context.Context, arg TouchAgentParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) + // An empty name names a new region after its key and keeps an existing name. + UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) + // Uptime per monitor from the hourly aggregate, including the not yet + // materialized most recent hours (real-time aggregation). + UptimeSince(ctx context.Context, arg UptimeSinceParams) ([]UptimeSinceRow, error) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) } diff --git a/internal/store/queries/agents.sql b/internal/store/queries/agents.sql new file mode 100644 index 0000000..e1b1282 --- /dev/null +++ b/internal/store/queries/agents.sql @@ -0,0 +1,26 @@ +-- name: UpsertRegion :one +-- An empty name names a new region after its key and keeps an existing name. +INSERT INTO regions (key, name) VALUES (sqlc.arg(key), coalesce(nullif(sqlc.arg(name)::text, ''), sqlc.arg(key))) +ON CONFLICT (key) DO UPDATE SET name = CASE WHEN sqlc.arg(name)::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING *; + +-- name: ListRegions :many +SELECT * FROM regions ORDER BY key; + +-- name: CreateAgent :one +INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING *; + +-- name: GetAgentByHash :one +SELECT * FROM agents WHERE token_hash = $1; + +-- name: ListAgents :many +SELECT * FROM agents ORDER BY kind, region, name; + +-- name: DeleteAgent :execrows +DELETE FROM agents WHERE id = $1; + +-- name: TouchAgent :exec +UPDATE agents SET last_seen_at = now(), release = $2 +WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 seconds' OR release IS DISTINCT FROM $2); diff --git a/internal/store/queries/check_results.sql b/internal/store/queries/check_results.sql new file mode 100644 index 0000000..2c6c8da --- /dev/null +++ b/internal/store/queries/check_results.sql @@ -0,0 +1,28 @@ +-- check_results and its aggregates have no row-level security (see +-- migration 00013). Every query here must filter by org_id. + +-- name: InsertCheckResults :copyfrom +INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9); + +-- name: LatestResults :many +-- Newest result per monitor and region in the org. +SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error +FROM check_results +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 +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > $3 +ORDER BY time DESC +LIMIT 500; + +-- name: UptimeSince :many +-- Uptime per monitor from the hourly aggregate, including the not yet +-- materialized most recent hours (real-time aggregation). +SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count +FROM check_results_1h +WHERE org_id = $1 AND bucket >= $2 +GROUP BY monitor_id; diff --git a/internal/store/queries/monitors.sql b/internal/store/queries/monitors.sql new file mode 100644 index 0000000..54d5fc5 --- /dev/null +++ b/internal/store/queries/monitors.sql @@ -0,0 +1,47 @@ +-- name: CreateMonitor :one +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING *; + +-- name: UpdateMonitor :one +UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, + timeout_ms = $6, config = $7, enabled = $8, updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: DeleteMonitor :execrows +DELETE FROM monitors WHERE id = $1; + +-- name: GetMonitor :one +SELECT * FROM monitors WHERE id = $1; + +-- name: ListMonitors :many +SELECT * FROM monitors ORDER BY name; + +-- name: MonitorRegions :many +SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region; + +-- name: AllMonitorRegions :many +SELECT monitor_id, region FROM monitor_regions; + +-- name: DeleteMonitorRegions :exec +DELETE FROM monitor_regions WHERE monitor_id = $1; + +-- name: AddMonitorRegion :exec +INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3); + +-- name: ListEnabledMonitorsForSchedule :many +-- System scope: every enabled monitor with its regions, for reconciling the +-- schedule. +SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id +WHERE m.enabled +GROUP BY m.id, m.interval_seconds; + +-- name: MonitorsForJobs :many +-- System scope: monitors to hand to a checker of region, skipping ones that +-- were disabled, deleted or moved out of the region since dispatch. +SELECT m.* FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) +WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled; diff --git a/internal/store/results_test.go b/internal/store/results_test.go new file mode 100644 index 0000000..f30de7f --- /dev/null +++ b/internal/store/results_test.go @@ -0,0 +1,30 @@ +package store + +import ( + "os" + "regexp" + "strings" + "testing" +) + +// TestResultQueriesFilterByOrg guards the tables that cannot use row-level +// security: every read of check results must be restricted to one org. +func TestResultQueriesFilterByOrg(t *testing.T) { + src, err := os.ReadFile("queries/check_results.sql") + if err != nil { + t.Fatal(err) + } + blocks := regexp.MustCompile(`(?m)^-- name: `).Split(string(src), -1)[1:] + if len(blocks) == 0 { + t.Fatal("no queries found") + } + for _, b := range blocks { + name, _, _ := strings.Cut(b, " ") + if strings.Contains(b, ":copyfrom") { + continue + } + if !regexp.MustCompile(`(?i)WHERE[^;]*\borg_id\s*=\s*\$1`).MatchString(b) { + t.Errorf("query %s does not filter by org_id = $1", name) + } + } +}