feat: organization-owned regions, checkers and status page servers #53

Merged
Sebi merged 3 commits from feat/org-agents into main 2026-11-22 00:47:25 +00:00
10 changed files with 442 additions and 99 deletions
Showing only changes of commit 607798d742 - Show all commits

No files matched your search

@@ -0,0 +1,104 @@
-- +goose Up
-- Regions, checkers and status page servers belong either to the platform
-- (org_id NULL, managed by platform admins, usable by every org) or to one
-- organization. Org-owned regions may reuse keys of other orgs, so regions
-- are now identified by id; check_results.region stores that id as text.
ALTER TABLE regions ADD COLUMN id uuid NOT NULL DEFAULT gen_random_uuid();
ALTER TABLE regions ADD COLUMN org_id uuid REFERENCES orgs (id) ON DELETE CASCADE;
ALTER TABLE monitor_regions ADD COLUMN region_id uuid;
UPDATE monitor_regions mr SET region_id = r.id FROM regions r WHERE r.key = mr.region;
ALTER TABLE agents ADD COLUMN region_id uuid;
UPDATE agents a SET region_id = r.id FROM regions r WHERE r.key = a.region;
UPDATE check_results c SET region = r.id::text FROM regions r WHERE r.key = c.region;
ALTER TABLE monitor_regions DROP CONSTRAINT monitor_regions_pkey;
ALTER TABLE monitor_regions DROP COLUMN region;
ALTER TABLE agents DROP CONSTRAINT agents_check;
ALTER TABLE agents DROP COLUMN region;
ALTER TABLE regions DROP CONSTRAINT regions_pkey;
ALTER TABLE regions ADD PRIMARY KEY (id);
ALTER TABLE regions ADD CONSTRAINT regions_owner_key_key UNIQUE NULLS NOT DISTINCT (org_id, key);
ALTER TABLE monitor_regions ALTER COLUMN region_id SET NOT NULL;
ALTER TABLE monitor_regions ADD PRIMARY KEY (monitor_id, region_id);
-- A region in use cannot be deleted; monitors have to move first.
ALTER TABLE monitor_regions ADD FOREIGN KEY (region_id) REFERENCES regions (id);
ALTER TABLE agents ADD FOREIGN KEY (region_id) REFERENCES regions (id);
ALTER TABLE agents ADD CONSTRAINT agents_checker_has_region CHECK ((kind = 'checker') = (region_id IS NOT NULL));
-- +goose StatementBegin
-- The region of an agent has the same owner as the agent, and monitors use
-- only platform regions or regions of their own org. A composite foreign
-- key cannot express this because platform rows have a NULL org_id.
CREATE FUNCTION region_owner(region uuid) RETURNS uuid
LANGUAGE sql STABLE AS $$ SELECT org_id FROM regions WHERE id = region $$;
CREATE FUNCTION agents_region_owner_check() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.region_id IS NOT NULL AND region_owner(NEW.region_id) IS DISTINCT FROM NEW.org_id THEN
RAISE EXCEPTION 'agent and region must have the same owner' USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END
$$;
CREATE FUNCTION monitor_regions_owner_check() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
owner uuid := region_owner(NEW.region_id);
BEGIN
IF owner IS NOT NULL AND owner <> NEW.org_id THEN
RAISE EXCEPTION 'region belongs to another organization' USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END
$$;
-- +goose StatementEnd
CREATE TRIGGER agents_region_owner BEFORE INSERT OR UPDATE ON agents
FOR EACH ROW EXECUTE FUNCTION agents_region_owner_check();
CREATE TRIGGER monitor_regions_owner BEFORE INSERT OR UPDATE ON monitor_regions
FOR EACH ROW EXECUTE FUNCTION monitor_regions_owner_check();
ALTER TABLE regions ENABLE ROW LEVEL SECURITY;
ALTER TABLE regions FORCE ROW LEVEL SECURITY;
CREATE POLICY regions_read ON regions FOR SELECT
USING (org_id IS NULL OR app_scope_system() OR org_id = app_org_id());
CREATE POLICY regions_write ON regions FOR ALL
USING (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id()))
WITH CHECK (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id()));
-- +goose Down
-- Only reversible while no organization owns regions.
DROP POLICY regions_write ON regions;
DROP POLICY regions_read ON regions;
ALTER TABLE regions NO FORCE ROW LEVEL SECURITY;
ALTER TABLE regions DISABLE ROW LEVEL SECURITY;
DROP TRIGGER monitor_regions_owner ON monitor_regions;
DROP TRIGGER agents_region_owner ON agents;
DROP FUNCTION monitor_regions_owner_check();
DROP FUNCTION agents_region_owner_check();
DROP FUNCTION region_owner(uuid);
ALTER TABLE monitor_regions ADD COLUMN region text;
UPDATE monitor_regions mr SET region = r.key FROM regions r WHERE r.id = mr.region_id;
ALTER TABLE agents ADD COLUMN region text;
UPDATE agents a SET region = r.key FROM regions r WHERE r.id = a.region_id;
UPDATE check_results c SET region = r.key FROM regions r WHERE r.id::text = c.region;
ALTER TABLE agents DROP CONSTRAINT agents_checker_has_region;
ALTER TABLE agents DROP COLUMN region_id;
ALTER TABLE monitor_regions DROP CONSTRAINT monitor_regions_pkey;
ALTER TABLE monitor_regions DROP COLUMN region_id;
ALTER TABLE regions DROP CONSTRAINT regions_owner_key_key;
ALTER TABLE regions DROP CONSTRAINT regions_pkey;
ALTER TABLE regions ADD PRIMARY KEY (key);
ALTER TABLE regions DROP COLUMN org_id;
ALTER TABLE regions DROP COLUMN id;
ALTER TABLE monitor_regions ALTER COLUMN region SET NOT NULL;
ALTER TABLE monitor_regions ADD PRIMARY KEY (monitor_id, region);
ALTER TABLE monitor_regions ADD FOREIGN KEY (region) REFERENCES regions (key);
ALTER TABLE agents ADD FOREIGN KEY (region) REFERENCES regions (key);
ALTER TABLE agents ADD CONSTRAINT agents_check CHECK ((kind = 'checker') = (region IS NOT NULL));
@@ -0,0 +1,8 @@
-- +goose Up
-- Platform admins manage what all organizations share: platform regions,
-- checkers and status page servers. Granted with "api admin grant"; the
-- first user of a self-hosted installation becomes one at signup.
ALTER TABLE users ADD COLUMN is_admin boolean NOT NULL DEFAULT false;
-- +goose Down
ALTER TABLE users DROP COLUMN is_admin;
+191 -43
View File
@@ -7,21 +7,22 @@ package store
import (
"context"
"time"
"github.com/google/uuid"
)
const createAgent = `-- name: CreateAgent :one
INSERT INTO agents (org_id, kind, name, region, token_hash, prefix)
INSERT INTO agents (org_id, kind, name, region_id, 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
RETURNING id, org_id, kind, name, token_hash, prefix, last_seen_at, release, created_at, region_id
`
type CreateAgentParams struct {
OrgID *uuid.UUID
Kind string
Name string
Region *string
RegionID *uuid.UUID
TokenHash []byte
Prefix string
}
@@ -31,7 +32,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
arg.OrgID,
arg.Kind,
arg.Name,
arg.Region,
arg.RegionID,
arg.TokenHash,
arg.Prefix,
)
@@ -41,74 +42,202 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
&i.OrgID,
&i.Kind,
&i.Name,
&i.Region,
&i.TokenHash,
&i.Prefix,
&i.LastSeenAt,
&i.Release,
&i.CreatedAt,
&i.RegionID,
)
return i, err
}
const createRegion = `-- name: CreateRegion :one
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
RETURNING key, name, created_at, id, org_id
`
type CreateRegionParams struct {
OrgID *uuid.UUID
Key string
Name string
}
func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) {
row := q.db.QueryRow(ctx, createRegion, arg.OrgID, arg.Key, arg.Name)
var i Region
err := row.Scan(
&i.Key,
&i.Name,
&i.CreatedAt,
&i.ID,
&i.OrgID,
)
return i, err
}
const deleteAgent = `-- name: DeleteAgent :execrows
DELETE FROM agents WHERE id = $1
DELETE FROM agents WHERE id = $1 AND org_id IS NOT DISTINCT FROM $2::uuid
`
func (q *Queries) DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deleteAgent, id)
type DeleteAgentParams struct {
ID uuid.UUID
OrgID *uuid.UUID
}
func (q *Queries) DeleteAgent(ctx context.Context, arg DeleteAgentParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteAgent, arg.ID, arg.OrgID)
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
const deleteRegion = `-- name: DeleteRegion :execrows
DELETE FROM regions WHERE id = $1
`
func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) {
func (q *Queries) DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deleteRegion, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const ensurePlatformRegion = `-- name: EnsurePlatformRegion :one
INSERT INTO regions (org_id, key, name)
VALUES (NULL, $1, coalesce(nullif($2::text, ''), $1))
ON CONFLICT ON CONSTRAINT regions_owner_key_key
DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END
RETURNING key, name, created_at, id, org_id
`
type EnsurePlatformRegionParams struct {
Key string
Name string
}
// An empty name names a new region after its key and keeps an existing name.
func (q *Queries) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error) {
row := q.db.QueryRow(ctx, ensurePlatformRegion, arg.Key, arg.Name)
var i Region
err := row.Scan(
&i.Key,
&i.Name,
&i.CreatedAt,
&i.ID,
&i.OrgID,
)
return i, err
}
const getAgentByHash = `-- name: GetAgentByHash :one
SELECT a.id, a.org_id, a.kind, a.name, a.token_hash, a.prefix, a.last_seen_at, a.release, a.created_at, a.region_id, r.key AS region_key, r.name AS region_name
FROM agents a
LEFT JOIN regions r ON r.id = a.region_id
WHERE a.token_hash = $1
`
type GetAgentByHashRow struct {
ID uuid.UUID
OrgID *uuid.UUID
Kind string
Name string
TokenHash []byte
Prefix string
LastSeenAt *time.Time
Release *string
CreatedAt time.Time
RegionID *uuid.UUID
RegionKey *string
RegionName *string
}
// System scope.
func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgentByHashRow, error) {
row := q.db.QueryRow(ctx, getAgentByHash, tokenHash)
var i Agent
var i GetAgentByHashRow
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Name,
&i.Region,
&i.TokenHash,
&i.Prefix,
&i.LastSeenAt,
&i.Release,
&i.CreatedAt,
&i.RegionID,
&i.RegionKey,
&i.RegionName,
)
return i, err
}
const getRegion = `-- name: GetRegion :one
SELECT key, name, created_at, id, org_id FROM regions WHERE id = $1
`
func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
row := q.db.QueryRow(ctx, getRegion, id)
var i Region
err := row.Scan(
&i.Key,
&i.Name,
&i.CreatedAt,
&i.ID,
&i.OrgID,
)
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
SELECT a.id, a.org_id, a.kind, a.name, a.token_hash, a.prefix, a.last_seen_at, a.release, a.created_at, a.region_id, r.key AS region_key, r.name AS region_name
FROM agents a
LEFT JOIN regions r ON r.id = a.region_id
WHERE a.org_id IS NOT DISTINCT FROM $1::uuid
ORDER BY a.kind, r.name, a.name
`
func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) {
rows, err := q.db.Query(ctx, listAgents)
type ListAgentsRow struct {
ID uuid.UUID
OrgID *uuid.UUID
Kind string
Name string
TokenHash []byte
Prefix string
LastSeenAt *time.Time
Release *string
CreatedAt time.Time
RegionID *uuid.UUID
RegionKey *string
RegionName *string
}
// Agents owned by org, or platform agents when org is NULL.
func (q *Queries) ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error) {
rows, err := q.db.Query(ctx, listAgents, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Agent{}
items := []ListAgentsRow{}
for rows.Next() {
var i Agent
var i ListAgentsRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Name,
&i.Region,
&i.TokenHash,
&i.Prefix,
&i.LastSeenAt,
&i.Release,
&i.CreatedAt,
&i.RegionID,
&i.RegionKey,
&i.RegionName,
); err != nil {
return nil, err
}
@@ -120,12 +249,12 @@ func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) {
return items, nil
}
const listRegions = `-- name: ListRegions :many
SELECT key, name, created_at FROM regions ORDER BY key
const listPlatformRegions = `-- name: ListPlatformRegions :many
SELECT key, name, created_at, id, org_id FROM regions WHERE org_id IS NULL ORDER BY name, key
`
func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) {
rows, err := q.db.Query(ctx, listRegions)
func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
rows, err := q.db.Query(ctx, listPlatformRegions)
if err != nil {
return nil, err
}
@@ -133,7 +262,45 @@ func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) {
items := []Region{}
for rows.Next() {
var i Region
if err := rows.Scan(&i.Key, &i.Name, &i.CreatedAt); err != nil {
if err := rows.Scan(
&i.Key,
&i.Name,
&i.CreatedAt,
&i.ID,
&i.OrgID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listVisibleRegions = `-- name: ListVisibleRegions :many
SELECT key, name, created_at, id, org_id FROM regions ORDER BY org_id IS NULL, name, key
`
// Row-level security limits this to platform regions and the scope's org;
// the org's own regions come first.
func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
rows, err := q.db.Query(ctx, listVisibleRegions)
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,
&i.ID,
&i.OrgID,
); err != nil {
return nil, err
}
items = append(items, i)
@@ -158,22 +325,3 @@ 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
}
+5 -2
View File
@@ -15,12 +15,12 @@ type Agent struct {
OrgID *uuid.UUID
Kind string
Name string
Region *string
TokenHash []byte
Prefix string
LastSeenAt *time.Time
Release *string
CreatedAt time.Time
RegionID *uuid.UUID
}
type ApiToken struct {
@@ -116,7 +116,7 @@ type Monitor struct {
type MonitorRegion struct {
MonitorID uuid.UUID
OrgID uuid.UUID
Region string
RegionID uuid.UUID
}
type Notification struct {
@@ -166,6 +166,8 @@ type Region struct {
Key string
Name string
CreatedAt time.Time
ID uuid.UUID
OrgID *uuid.UUID
}
type Role struct {
@@ -215,6 +217,7 @@ type User struct {
TotpSecret []byte
TotpEnabledAt *time.Time
Locale *string
IsAdmin bool
}
type UserIdentity struct {
+28 -23
View File
@@ -12,27 +12,27 @@ import (
)
const addMonitorRegion = `-- name: AddMonitorRegion :exec
INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3)
INSERT INTO monitor_regions (monitor_id, org_id, region_id) VALUES ($1, $2, $3)
`
type AddMonitorRegionParams struct {
MonitorID uuid.UUID
OrgID uuid.UUID
Region string
RegionID uuid.UUID
}
func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error {
_, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.Region)
_, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.RegionID)
return err
}
const allMonitorRegions = `-- name: AllMonitorRegions :many
SELECT monitor_id, region FROM monitor_regions
SELECT monitor_id, region_id FROM monitor_regions
`
type AllMonitorRegionsRow struct {
MonitorID uuid.UUID
Region string
RegionID uuid.UUID
}
func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) {
@@ -44,7 +44,7 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow
items := []AllMonitorRegionsRow{}
for rows.Next() {
var i AllMonitorRegionsRow
if err := rows.Scan(&i.MonitorID, &i.Region); err != nil {
if err := rows.Scan(&i.MonitorID, &i.RegionID); err != nil {
return nil, err
}
items = append(items, i)
@@ -149,7 +149,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
}
const listEnabledMonitorsForSchedule = `-- name: ListEnabledMonitorsForSchedule :many
SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions
SELECT m.id, m.interval_seconds, array_agg(r.region_id::text ORDER BY r.region_id)::text[] AS regions
FROM monitors m
JOIN monitor_regions r ON r.monitor_id = m.id
WHERE m.enabled
@@ -222,22 +222,22 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
}
const monitorRegions = `-- name: MonitorRegions :many
SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region
SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id
`
func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) {
func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, monitorRegions, monitorID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []string{}
items := []uuid.UUID{}
for rows.Next() {
var region string
if err := rows.Scan(&region); err != nil {
var region_id uuid.UUID
if err := rows.Scan(&region_id); err != nil {
return nil, err
}
items = append(items, region)
items = append(items, region_id)
}
if err := rows.Err(); err != nil {
return nil, err
@@ -247,19 +247,22 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]st
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, m.confirmations FROM monitors m
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1
WHERE m.id = ANY ($2::uuid[]) AND m.enabled
AND ($3::uuid IS NULL OR m.org_id = $3)
`
type MonitorsForJobsParams struct {
Region string
Ids []uuid.UUID
RegionID uuid.UUID
Ids []uuid.UUID
AgentOrg *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.
// were disabled, deleted or moved out of the region since dispatch. An
// org-owned checker only ever sees its org's monitors.
func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) {
rows, err := q.db.Query(ctx, monitorsForJobs, arg.Region, arg.Ids)
rows, err := q.db.Query(ctx, monitorsForJobs, arg.RegionID, arg.Ids, arg.AgentOrg)
if err != nil {
return nil, err
}
@@ -293,15 +296,17 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams
const monitorsForResults = `-- name: MonitorsForResults :many
SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations,
(SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
(SELECT array_agg(r2.region_id::text ORDER BY r2.region_id) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
FROM monitors m
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1
WHERE m.id = ANY ($2::uuid[]) AND m.enabled
AND ($3::uuid IS NULL OR m.org_id = $3)
`
type MonitorsForResultsParams struct {
Region string
Ids []uuid.UUID
RegionID uuid.UUID
Ids []uuid.UUID
AgentOrg *uuid.UUID
}
type MonitorsForResultsRow struct {
@@ -317,7 +322,7 @@ type MonitorsForResultsRow struct {
// System scope: monitors a checker of region may report, with every region
// they are assigned to, for evaluation.
func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error) {
rows, err := q.db.Query(ctx, monitorsForResults, arg.Region, arg.Ids)
rows, err := q.db.Query(ctx, monitorsForResults, arg.RegionID, arg.Ids, arg.AgentOrg)
if err != nil {
return nil, err
}
+19 -8
View File
@@ -31,11 +31,12 @@ type Querier interface {
CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error)
CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error)
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, 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)
DeleteAgent(ctx context.Context, arg DeleteAgentParams) (int64, error)
DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error)
DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error)
DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error)
@@ -43,15 +44,19 @@ type Querier interface {
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
DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error)
DeleteRole(ctx context.Context, id uuid.UUID) (int64, error)
DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error)
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
DisableTOTP(ctx context.Context, id uuid.UUID) error
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
// An empty name names a new region after its key and keeps an existing name.
EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, 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)
// System scope.
GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgentByHashRow, error)
GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error)
GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error)
GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error)
@@ -61,6 +66,7 @@ type Querier interface {
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)
GetRegion(ctx context.Context, id uuid.UUID) (Region, 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)
@@ -75,7 +81,8 @@ type Querier interface {
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error)
ListAgents(ctx context.Context) ([]Agent, error)
// Agents owned by org, or platform agents when org is NULL.
ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error)
ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error)
ListChannels(ctx context.Context) ([]NotificationChannel, error)
ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error)
@@ -88,19 +95,24 @@ type Querier interface {
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)
ListPlatformRegions(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)
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
// Row-level security limits this to platform regions and the scope's org;
// the org's own regions come first.
ListVisibleRegions(ctx context.Context) ([]Region, error)
MakeAdmin(ctx context.Context, id uuid.UUID) error
MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error)
MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error
MarkNotificationSent(ctx context.Context, id uuid.UUID) 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)
MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, 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.
// were disabled, deleted or moved out of the region since dispatch. An
// org-owned checker only ever sees its org's monitors.
MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error)
// System scope: monitors a checker of region may report, with every region
// they are assigned to, for evaluation.
@@ -113,6 +125,7 @@ type Querier interface {
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
TouchAPIToken(ctx context.Context, id uuid.UUID) error
TouchAgent(ctx context.Context, arg TouchAgentParams) error
@@ -122,8 +135,6 @@ type Querier interface {
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)
+36 -10
View File
@@ -1,25 +1,51 @@
-- 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
-- name: CreateRegion :one
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
RETURNING *;
-- name: ListRegions :many
SELECT * FROM regions ORDER BY key;
-- name: EnsurePlatformRegion :one
-- An empty name names a new region after its key and keeps an existing name.
INSERT INTO regions (org_id, key, name)
VALUES (NULL, sqlc.arg(key), coalesce(nullif(sqlc.arg(name)::text, ''), sqlc.arg(key)))
ON CONFLICT ON CONSTRAINT regions_owner_key_key
DO UPDATE SET name = CASE WHEN sqlc.arg(name)::text = '' THEN regions.name ELSE EXCLUDED.name END
RETURNING *;
-- name: GetRegion :one
SELECT * FROM regions WHERE id = $1;
-- name: ListVisibleRegions :many
-- Row-level security limits this to platform regions and the scope's org;
-- the org's own regions come first.
SELECT * FROM regions ORDER BY org_id IS NULL, name, key;
-- name: ListPlatformRegions :many
SELECT * FROM regions WHERE org_id IS NULL ORDER BY name, key;
-- name: DeleteRegion :execrows
DELETE FROM regions WHERE id = $1;
-- name: CreateAgent :one
INSERT INTO agents (org_id, kind, name, region, token_hash, prefix)
INSERT INTO agents (org_id, kind, name, region_id, token_hash, prefix)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
-- name: GetAgentByHash :one
SELECT * FROM agents WHERE token_hash = $1;
-- System scope.
SELECT a.*, r.key AS region_key, r.name AS region_name
FROM agents a
LEFT JOIN regions r ON r.id = a.region_id
WHERE a.token_hash = $1;
-- name: ListAgents :many
SELECT * FROM agents ORDER BY kind, region, name;
-- Agents owned by org, or platform agents when org is NULL.
SELECT a.*, r.key AS region_key, r.name AS region_name
FROM agents a
LEFT JOIN regions r ON r.id = a.region_id
WHERE a.org_id IS NOT DISTINCT FROM sqlc.narg(org_id)::uuid
ORDER BY a.kind, r.name, a.name;
-- name: DeleteAgent :execrows
DELETE FROM agents WHERE id = $1;
DELETE FROM agents WHERE id = sqlc.arg(id) AND org_id IS NOT DISTINCT FROM sqlc.narg(org_id)::uuid;
-- name: TouchAgent :exec
UPDATE agents SET last_seen_at = now(), release = $2
+13 -10
View File
@@ -19,21 +19,21 @@ SELECT * FROM monitors WHERE id = $1;
SELECT * FROM monitors ORDER BY name;
-- name: MonitorRegions :many
SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region;
SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id;
-- name: AllMonitorRegions :many
SELECT monitor_id, region FROM monitor_regions;
SELECT monitor_id, region_id 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);
INSERT INTO monitor_regions (monitor_id, org_id, region_id) 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
SELECT m.id, m.interval_seconds, array_agg(r.region_id::text ORDER BY r.region_id)::text[] AS regions
FROM monitors m
JOIN monitor_regions r ON r.monitor_id = m.id
WHERE m.enabled
@@ -41,16 +41,19 @@ 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.
-- were disabled, deleted or moved out of the region since dispatch. An
-- org-owned checker only ever sees its org's monitors.
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;
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = sqlc.arg(region_id)
WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled
AND (sqlc.narg(agent_org)::uuid IS NULL OR m.org_id = sqlc.narg(agent_org));
-- name: MonitorsForResults :many
-- System scope: monitors a checker of region may report, with every region
-- they are assigned to, for evaluation.
SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations,
(SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
(SELECT array_agg(r2.region_id::text ORDER BY r2.region_id) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
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;
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = sqlc.arg(region_id)
WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled
AND (sqlc.narg(agent_org)::uuid IS NULL OR m.org_id = sqlc.narg(agent_org));
+6
View File
@@ -25,3 +25,9 @@ DELETE FROM users WHERE id = $1;
-- name: SetUserLocale :exec
UPDATE users SET locale = $2, updated_at = now() WHERE id = $1;
-- name: SetUserAdmin :execrows
UPDATE users SET is_admin = $2, updated_at = now() WHERE email = $1;
-- name: MakeAdmin :exec
UPDATE users SET is_admin = true, updated_at = now() WHERE id = $1;
+32 -3
View File
@@ -24,7 +24,7 @@ func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) {
const createUser = `-- name: CreateUser :one
INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4)
RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale
RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin
`
type CreateUserParams struct {
@@ -53,6 +53,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
&i.TotpSecret,
&i.TotpEnabledAt,
&i.Locale,
&i.IsAdmin,
)
return i, err
}
@@ -93,7 +94,7 @@ func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error {
}
const getUser = `-- name: GetUser :one
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE id = $1
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin FROM users WHERE id = $1
`
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) {
@@ -110,12 +111,13 @@ func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) {
&i.TotpSecret,
&i.TotpEnabledAt,
&i.Locale,
&i.IsAdmin,
)
return i, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE email = $1
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin FROM users WHERE email = $1
`
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
@@ -132,10 +134,20 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
&i.TotpSecret,
&i.TotpEnabledAt,
&i.Locale,
&i.IsAdmin,
)
return i, err
}
const makeAdmin = `-- name: MakeAdmin :exec
UPDATE users SET is_admin = true, updated_at = now() WHERE id = $1
`
func (q *Queries) MakeAdmin(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, makeAdmin, id)
return err
}
const setPasswordHash = `-- name: SetPasswordHash :exec
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
`
@@ -150,6 +162,23 @@ func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams
return err
}
const setUserAdmin = `-- name: SetUserAdmin :execrows
UPDATE users SET is_admin = $2, updated_at = now() WHERE email = $1
`
type SetUserAdminParams struct {
Email string
IsAdmin bool
}
func (q *Queries) SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) {
result, err := q.db.Exec(ctx, setUserAdmin, arg.Email, arg.IsAdmin)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setUserLocale = `-- name: SetUserLocale :exec
UPDATE users SET locale = $2, updated_at = now() WHERE id = $1
`