From 2d7f326d385ce5f6cc689a0183c7af2d0583202c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 09:19:55 +0100 Subject: [PATCH] feat(store): add nested monitor groups A trigger rejects cycles and nesting deeper than eight levels; composite foreign keys keep groups and their monitors in one organization. Refs #57 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .../migrations/sql/00021_monitor_groups.sql | 69 +++++++ internal/store/models.go | 10 ++ internal/store/monitor_groups.sql.go | 169 ++++++++++++++++++ internal/store/monitors.sql.go | 25 ++- internal/store/querier.go | 9 + internal/store/queries/monitor_groups.sql | 29 +++ internal/store/queries/monitors.sql | 6 +- 7 files changed, 306 insertions(+), 11 deletions(-) create mode 100644 internal/migrations/sql/00021_monitor_groups.sql create mode 100644 internal/store/monitor_groups.sql.go create mode 100644 internal/store/queries/monitor_groups.sql diff --git a/internal/migrations/sql/00021_monitor_groups.sql b/internal/migrations/sql/00021_monitor_groups.sql new file mode 100644 index 0000000..5783318 --- /dev/null +++ b/internal/migrations/sql/00021_monitor_groups.sql @@ -0,0 +1,69 @@ +-- +goose Up +CREATE TABLE monitor_groups ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + parent_id uuid, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (id, org_id), + CHECK (parent_id IS DISTINCT FROM id), + -- Composite keys keep parents and members in the same organization; + -- removing a group detaches what referenced it instead of failing. + FOREIGN KEY (parent_id, org_id) REFERENCES monitor_groups (id, org_id) ON DELETE SET NULL (parent_id) +); + +CREATE INDEX monitor_groups_parent_idx ON monitor_groups (parent_id); + +ALTER TABLE monitors ADD COLUMN group_id uuid; +ALTER TABLE monitors ADD FOREIGN KEY (group_id, org_id) REFERENCES monitor_groups (id, org_id) ON DELETE SET NULL (group_id); +CREATE INDEX monitors_group_idx ON monitors (group_id); + +-- +goose StatementBegin +-- Rejects cycles and nesting deeper than eight levels. +CREATE FUNCTION monitor_groups_tree_check() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + depth integer; +BEGIN + IF NEW.parent_id IS NULL THEN + RETURN NEW; + END IF; + WITH RECURSIVE up AS ( + SELECT id, parent_id, 1 AS depth FROM monitor_groups WHERE id = NEW.parent_id + UNION ALL + SELECT g.id, g.parent_id, up.depth + 1 FROM monitor_groups g JOIN up ON g.id = up.parent_id + WHERE up.depth < 20 + ) + SELECT max(up.depth) INTO depth FROM up; + IF EXISTS ( + WITH RECURSIVE up AS ( + SELECT id, parent_id FROM monitor_groups WHERE id = NEW.parent_id + UNION + SELECT g.id, g.parent_id FROM monitor_groups g JOIN up ON g.id = up.parent_id + ) + SELECT 1 FROM up WHERE id = NEW.id + ) THEN + RAISE EXCEPTION 'monitor group cycle' USING ERRCODE = 'check_violation', CONSTRAINT = 'monitor_groups_cycle'; + END IF; + IF depth >= 8 THEN + RAISE EXCEPTION 'monitor groups nested too deeply' USING ERRCODE = 'check_violation', CONSTRAINT = 'monitor_groups_depth'; + END IF; + RETURN NEW; +END +$$; +-- +goose StatementEnd + +CREATE TRIGGER monitor_groups_tree BEFORE INSERT OR UPDATE OF parent_id ON monitor_groups + FOR EACH ROW EXECUTE FUNCTION monitor_groups_tree_check(); + +ALTER TABLE monitor_groups ENABLE ROW LEVEL SECURITY; +ALTER TABLE monitor_groups FORCE ROW LEVEL SECURITY; +CREATE POLICY monitor_groups_tenant ON monitor_groups 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 +ALTER TABLE monitors DROP COLUMN group_id; +DROP TABLE monitor_groups; +DROP FUNCTION monitor_groups_tree_check(); diff --git a/internal/store/models.go b/internal/store/models.go index b1c8906..b08821e 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -118,6 +118,16 @@ type Monitor struct { CreatedAt time.Time UpdatedAt time.Time Confirmations int32 + GroupID *uuid.UUID +} + +type MonitorGroup struct { + ID uuid.UUID + OrgID uuid.UUID + ParentID *uuid.UUID + Name string + CreatedAt time.Time + UpdatedAt time.Time } type MonitorRegion struct { diff --git a/internal/store/monitor_groups.sql.go b/internal/store/monitor_groups.sql.go new file mode 100644 index 0000000..9707363 --- /dev/null +++ b/internal/store/monitor_groups.sql.go @@ -0,0 +1,169 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: monitor_groups.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const createGroup = `-- name: CreateGroup :one +INSERT INTO monitor_groups (org_id, parent_id, name) VALUES ($1, $2, $3) +RETURNING id, org_id, parent_id, name, created_at, updated_at +` + +type CreateGroupParams struct { + OrgID uuid.UUID + ParentID *uuid.UUID + Name string +} + +func (q *Queries) CreateGroup(ctx context.Context, arg CreateGroupParams) (MonitorGroup, error) { + row := q.db.QueryRow(ctx, createGroup, arg.OrgID, arg.ParentID, arg.Name) + var i MonitorGroup + err := row.Scan( + &i.ID, + &i.OrgID, + &i.ParentID, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteAssignmentsForResource = `-- name: DeleteAssignmentsForResource :exec +DELETE FROM role_assignments WHERE resource_type = $1 AND resource_id = $2 +` + +type DeleteAssignmentsForResourceParams struct { + ResourceType *string + ResourceID *uuid.UUID +} + +func (q *Queries) DeleteAssignmentsForResource(ctx context.Context, arg DeleteAssignmentsForResourceParams) error { + _, err := q.db.Exec(ctx, deleteAssignmentsForResource, arg.ResourceType, arg.ResourceID) + return err +} + +const deleteGroup = `-- name: DeleteGroup :execrows +DELETE FROM monitor_groups WHERE id = $1 +` + +func (q *Queries) DeleteGroup(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteGroup, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getGroup = `-- name: GetGroup :one +SELECT id, org_id, parent_id, name, created_at, updated_at FROM monitor_groups WHERE id = $1 +` + +func (q *Queries) GetGroup(ctx context.Context, id uuid.UUID) (MonitorGroup, error) { + row := q.db.QueryRow(ctx, getGroup, id) + var i MonitorGroup + err := row.Scan( + &i.ID, + &i.OrgID, + &i.ParentID, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const listGroups = `-- name: ListGroups :many +SELECT id, org_id, parent_id, name, created_at, updated_at FROM monitor_groups ORDER BY name +` + +func (q *Queries) ListGroups(ctx context.Context) ([]MonitorGroup, error) { + rows, err := q.db.Query(ctx, listGroups) + if err != nil { + return nil, err + } + defer rows.Close() + items := []MonitorGroup{} + for rows.Next() { + var i MonitorGroup + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.ParentID, + &i.Name, + &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 regroupMonitors = `-- name: RegroupMonitors :exec +UPDATE monitors SET group_id = $1, updated_at = now() +WHERE group_id = $2 +` + +type RegroupMonitorsParams struct { + NewGroup *uuid.UUID + OldGroup *uuid.UUID +} + +func (q *Queries) RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error { + _, err := q.db.Exec(ctx, regroupMonitors, arg.NewGroup, arg.OldGroup) + return err +} + +const reparentGroups = `-- name: ReparentGroups :exec +UPDATE monitor_groups SET parent_id = $1, updated_at = now() +WHERE parent_id = $2 +` + +type ReparentGroupsParams struct { + NewParent *uuid.UUID + OldParent *uuid.UUID +} + +// Moves the subgroups of a group that is about to be deleted. +func (q *Queries) ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error { + _, err := q.db.Exec(ctx, reparentGroups, arg.NewParent, arg.OldParent) + return err +} + +const updateGroup = `-- name: UpdateGroup :one +UPDATE monitor_groups SET name = $2, parent_id = $3, updated_at = now() +WHERE id = $1 +RETURNING id, org_id, parent_id, name, created_at, updated_at +` + +type UpdateGroupParams struct { + ID uuid.UUID + Name string + ParentID *uuid.UUID +} + +func (q *Queries) UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error) { + row := q.db.QueryRow(ctx, updateGroup, arg.ID, arg.Name, arg.ParentID) + var i MonitorGroup + err := row.Scan( + &i.ID, + &i.OrgID, + &i.ParentID, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/monitors.sql.go b/internal/store/monitors.sql.go index ca70fdc..91301d3 100644 --- a/internal/store/monitors.sql.go +++ b/internal/store/monitors.sql.go @@ -56,9 +56,9 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow } const createMonitor = `-- name: CreateMonitor :one -INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) -RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations, group_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id ` type CreateMonitorParams struct { @@ -71,6 +71,7 @@ type CreateMonitorParams struct { Config []byte Enabled bool Confirmations int32 + GroupID *uuid.UUID } func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) { @@ -84,6 +85,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M arg.Config, arg.Enabled, arg.Confirmations, + arg.GroupID, ) var i Monitor err := row.Scan( @@ -99,6 +101,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M &i.CreatedAt, &i.UpdatedAt, &i.Confirmations, + &i.GroupID, ) return i, err } @@ -125,7 +128,7 @@ func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) } const getMonitor = `-- name: GetMonitor :one -SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors WHERE id = $1 +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors WHERE id = $1 ` func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) { @@ -144,6 +147,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) &i.CreatedAt, &i.UpdatedAt, &i.Confirmations, + &i.GroupID, ) return i, err } @@ -185,7 +189,7 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna } const listMonitors = `-- name: ListMonitors :many -SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors ORDER BY name +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors ORDER BY name ` func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { @@ -210,6 +214,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { &i.CreatedAt, &i.UpdatedAt, &i.Confirmations, + &i.GroupID, ); err != nil { return nil, err } @@ -246,7 +251,7 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uu } 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 +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, m.group_id FROM monitors m 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) @@ -283,6 +288,7 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams &i.CreatedAt, &i.UpdatedAt, &i.Confirmations, + &i.GroupID, ); err != nil { return nil, err } @@ -351,9 +357,9 @@ func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResults const updateMonitor = `-- name: UpdateMonitor :one UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, - timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now() + timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, group_id = $10, updated_at = now() WHERE id = $1 -RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id ` type UpdateMonitorParams struct { @@ -366,6 +372,7 @@ type UpdateMonitorParams struct { Config []byte Enabled bool Confirmations int32 + GroupID *uuid.UUID } func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) { @@ -379,6 +386,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M arg.Config, arg.Enabled, arg.Confirmations, + arg.GroupID, ) var i Monitor err := row.Scan( @@ -394,6 +402,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M &i.CreatedAt, &i.UpdatedAt, &i.Confirmations, + &i.GroupID, ) return i, err } diff --git a/internal/store/querier.go b/internal/store/querier.go index 44f0bd6..206e5a9 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -29,6 +29,7 @@ type Querier interface { CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error) + CreateGroup(ctx context.Context, arg CreateGroupParams) (MonitorGroup, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) @@ -43,7 +44,9 @@ type Querier interface { DeleteAPIToken(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) + DeleteAssignmentsForResource(ctx context.Context, arg DeleteAssignmentsForResourceParams) error DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error) + DeleteGroup(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 @@ -68,6 +71,7 @@ type Querier interface { 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) + GetGroup(ctx context.Context, id uuid.UUID) (MonitorGroup, 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) @@ -103,6 +107,7 @@ type Querier interface { // schedule. ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) + ListGroups(ctx context.Context) ([]MonitorGroup, error) ListIncidents(ctx context.Context) ([]ListIncidentsRow, error) ListMonitors(ctx context.Context) ([]Monitor, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) @@ -139,7 +144,10 @@ type Querier interface { OpenIncidents(ctx context.Context) ([]Incident, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) + RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) + // Moves the subgroups of a group that is about to be deleted. + ReparentGroups(ctx context.Context, arg ReparentGroupsParams) error ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error // Changing the domain drops a previous verification. @@ -156,6 +164,7 @@ type Querier interface { TouchAgent(ctx context.Context, arg TouchAgentParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) + UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, 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) diff --git a/internal/store/queries/monitor_groups.sql b/internal/store/queries/monitor_groups.sql new file mode 100644 index 0000000..6170df1 --- /dev/null +++ b/internal/store/queries/monitor_groups.sql @@ -0,0 +1,29 @@ +-- name: CreateGroup :one +INSERT INTO monitor_groups (org_id, parent_id, name) VALUES ($1, $2, $3) +RETURNING *; + +-- name: UpdateGroup :one +UPDATE monitor_groups SET name = $2, parent_id = $3, updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: GetGroup :one +SELECT * FROM monitor_groups WHERE id = $1; + +-- name: ListGroups :many +SELECT * FROM monitor_groups ORDER BY name; + +-- name: ReparentGroups :exec +-- Moves the subgroups of a group that is about to be deleted. +UPDATE monitor_groups SET parent_id = sqlc.narg(new_parent), updated_at = now() +WHERE parent_id = sqlc.arg(old_parent); + +-- name: RegroupMonitors :exec +UPDATE monitors SET group_id = sqlc.narg(new_group), updated_at = now() +WHERE group_id = sqlc.arg(old_group); + +-- name: DeleteGroup :execrows +DELETE FROM monitor_groups WHERE id = $1; + +-- name: DeleteAssignmentsForResource :exec +DELETE FROM role_assignments WHERE resource_type = $1 AND resource_id = $2; diff --git a/internal/store/queries/monitors.sql b/internal/store/queries/monitors.sql index 5674820..8e59479 100644 --- a/internal/store/queries/monitors.sql +++ b/internal/store/queries/monitors.sql @@ -1,11 +1,11 @@ -- name: CreateMonitor :one -INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations, group_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *; -- name: UpdateMonitor :one UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, - timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now() + timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, group_id = $10, updated_at = now() WHERE id = $1 RETURNING *;