feat(store): add monitors, regions, agents and check result hypertable
check_results has no row-level security because TimescaleDB refuses compression and continuous aggregates on such tables. Every results query takes org_id as a parameter, which a test enforces. Refs #10, #13 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
55559c8b0a
commit
00658d49a2
12 files changed
+1093
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user