Adds the organisation routes the single binary's dashboard needs (list, get, workspace list and create) plus owner-only renames of the organisation and its workspaces. A rename is guarded by the version the caller read, writes only the display label, and appends an actor-attributed event in governance.org_events in the same transaction. The Organisation page shows those name changes, and a deep link is no longer replaced by the landing page while the router is still resolving it. Refs #2077
407 lines
15 KiB
Go
407 lines
15 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// OrgRow is a tenant row in governance.orgs.
|
|
type OrgRow struct {
|
|
ID string `db:"id"`
|
|
Name string `db:"name"`
|
|
Version int64 `db:"version"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
UpdatedAt time.Time `db:"updated_at"`
|
|
}
|
|
|
|
// WorkspaceRow is a workspace row in governance.workspaces.
|
|
type WorkspaceRow struct {
|
|
ID string `db:"id"`
|
|
OrgID string `db:"org_id"`
|
|
Name string `db:"name"`
|
|
Environment string `db:"environment"`
|
|
Version int64 `db:"version"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
UpdatedAt time.Time `db:"updated_at"`
|
|
}
|
|
|
|
// OrgEventRow is one appended name change in governance.org_events. WorkspaceID
|
|
// is empty when the event renamed the organisation itself.
|
|
type OrgEventRow struct {
|
|
ID int64 `db:"id"`
|
|
OrgID string `db:"org_id"`
|
|
WorkspaceID string `db:"workspace_id"`
|
|
Type string `db:"event_type"`
|
|
ActorID string `db:"actor_id"`
|
|
ActorName string `db:"actor_name"`
|
|
RequestID string `db:"request_id"`
|
|
OldName string `db:"old_name"`
|
|
NewName string `db:"new_name"`
|
|
At time.Time `db:"at"`
|
|
}
|
|
|
|
// MembershipRow is a role assignment in governance.memberships.
|
|
type MembershipRow struct {
|
|
IdentityID string `db:"identity_id"`
|
|
OrgID string `db:"org_id"`
|
|
WorkspaceID sql.NullString `db:"workspace_id"`
|
|
Role string `db:"role"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
}
|
|
|
|
// MemberRow joins a membership with its identity's kind and display name.
|
|
type MemberRow struct {
|
|
IdentityID string `db:"identity_id"`
|
|
Kind string `db:"kind"`
|
|
DisplayName string `db:"display_name"`
|
|
WorkspaceID sql.NullString `db:"workspace_id"`
|
|
Role string `db:"role"`
|
|
}
|
|
|
|
// AgentAssignmentRow is an agent's owning org in governance.org_agents.
|
|
type AgentAssignmentRow struct {
|
|
IdentityID string `db:"identity_id"`
|
|
OrgID string `db:"org_id"`
|
|
}
|
|
|
|
// CreateOrg inserts an org, its default workspace, and its initial owner membership.
|
|
func (s *Store) CreateOrg(ctx context.Context, id, name, defaultWorkspaceID, ownerIdentityID string) error {
|
|
return s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
if _, err := tx.ExecContext(ctx, `INSERT INTO governance.orgs (id, name) VALUES ($1, $2)`, id, name); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return fmt.Errorf("%w: %s", ErrAlreadyExists, id)
|
|
}
|
|
return fmt.Errorf("insert org: %w", err)
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.workspaces (id, org_id, name) VALUES ($1, $2, 'Default')`,
|
|
defaultWorkspaceID, id); err != nil {
|
|
return fmt.Errorf("insert default workspace: %w", err)
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.memberships (identity_id, org_id, role)
|
|
VALUES ($1, $2, 'owner')
|
|
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`,
|
|
ownerIdentityID, id); err != nil {
|
|
return fmt.Errorf("insert org owner: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// GetOrg returns one org row; ok is false when not found.
|
|
func (s *Store) GetOrg(ctx context.Context, id string) (OrgRow, bool, error) {
|
|
var out OrgRow
|
|
err := s.db.GetContext(ctx, &out, `SELECT id, name, version, created_at, updated_at FROM governance.orgs WHERE id = $1`, id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return OrgRow{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return OrgRow{}, false, fmt.Errorf("read org: %w", err)
|
|
}
|
|
return out, true, nil
|
|
}
|
|
|
|
// ListOrgs returns every org row, oldest first.
|
|
func (s *Store) ListOrgs(ctx context.Context) ([]OrgRow, error) {
|
|
var out []OrgRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, name, version, created_at, updated_at FROM governance.orgs ORDER BY created_at, id`); err != nil {
|
|
return nil, fmt.Errorf("list orgs: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// CreateWorkspace inserts a workspace into an existing org.
|
|
func (s *Store) CreateWorkspace(ctx context.Context, w WorkspaceRow) error {
|
|
if _, ok, err := s.GetOrg(ctx, w.OrgID); err != nil {
|
|
return err
|
|
} else if !ok {
|
|
return ErrNotFound
|
|
}
|
|
if _, err := s.db.ExecContext(ctx, `
|
|
INSERT INTO governance.workspaces (id, org_id, name, environment) VALUES ($1, $2, $3, $4)`,
|
|
w.ID, w.OrgID, w.Name, w.Environment); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return fmt.Errorf("%w: %s/%s", ErrAlreadyExists, w.OrgID, w.ID)
|
|
}
|
|
return fmt.Errorf("create workspace: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListWorkspaces returns an org's workspaces, oldest first.
|
|
func (s *Store) ListWorkspaces(ctx context.Context, orgID string) ([]WorkspaceRow, error) {
|
|
var out []WorkspaceRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, name, environment, version, created_at, updated_at
|
|
FROM governance.workspaces WHERE org_id = $1 ORDER BY created_at, id`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list workspaces: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RenameOrg changes an org's display name when its version still matches
|
|
// expected and appends event in the same transaction. A rename to the current
|
|
// name writes nothing, so no audit entry claims a change that did not happen.
|
|
func (s *Store) RenameOrg(ctx context.Context, id, name string, expected int64, event OrgEventRow) (OrgRow, error) {
|
|
var out OrgRow
|
|
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
var current OrgRow
|
|
if err := tx.GetContext(ctx, ¤t, `
|
|
SELECT id, name, version, created_at, updated_at FROM governance.orgs
|
|
WHERE id = $1 FOR UPDATE`, id); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return ErrNotFound
|
|
}
|
|
return fmt.Errorf("read org: %w", err)
|
|
}
|
|
if current.Version != expected {
|
|
return ErrVersionConflict
|
|
}
|
|
if current.Name == name {
|
|
out = current
|
|
return nil
|
|
}
|
|
if err := tx.GetContext(ctx, &out, `
|
|
UPDATE governance.orgs SET name = $2, version = version + 1, updated_at = now()
|
|
WHERE id = $1
|
|
RETURNING id, name, version, created_at, updated_at`, id, name); err != nil {
|
|
return fmt.Errorf("rename org: %w", err)
|
|
}
|
|
event.OrgID, event.OldName, event.NewName = id, current.Name, name
|
|
return insertOrgEvent(ctx, tx, event)
|
|
})
|
|
return out, err
|
|
}
|
|
|
|
// RenameWorkspace changes one workspace's display name inside orgID when its
|
|
// version still matches expected and appends event in the same transaction.
|
|
func (s *Store) RenameWorkspace(ctx context.Context, orgID, id, name string, expected int64, event OrgEventRow) (WorkspaceRow, error) {
|
|
var out WorkspaceRow
|
|
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
var current WorkspaceRow
|
|
if err := tx.GetContext(ctx, ¤t, `
|
|
SELECT id, org_id, name, environment, version, created_at, updated_at
|
|
FROM governance.workspaces WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return ErrNotFound
|
|
}
|
|
return fmt.Errorf("read workspace: %w", err)
|
|
}
|
|
if current.Version != expected {
|
|
return ErrVersionConflict
|
|
}
|
|
if current.Name == name {
|
|
out = current
|
|
return nil
|
|
}
|
|
if err := tx.GetContext(ctx, &out, `
|
|
UPDATE governance.workspaces SET name = $3, version = version + 1, updated_at = now()
|
|
WHERE org_id = $1 AND id = $2
|
|
RETURNING id, org_id, name, environment, version, created_at, updated_at`,
|
|
orgID, id, name); err != nil {
|
|
return fmt.Errorf("rename workspace: %w", err)
|
|
}
|
|
event.OrgID, event.WorkspaceID, event.OldName, event.NewName = orgID, id, current.Name, name
|
|
return insertOrgEvent(ctx, tx, event)
|
|
})
|
|
return out, err
|
|
}
|
|
|
|
func insertOrgEvent(ctx context.Context, tx *sqlx.Tx, ev OrgEventRow) error {
|
|
_, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.org_events
|
|
(org_id, workspace_id, event_type, actor_id, actor_name, request_id, old_name, new_name)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
|
ev.OrgID, ev.WorkspaceID, ev.Type, ev.ActorID, ev.ActorName, ev.RequestID, ev.OldName, ev.NewName)
|
|
return err
|
|
}
|
|
|
|
// ListOrgEvents returns an org's appended name changes, newest first.
|
|
func (s *Store) ListOrgEvents(ctx context.Context, orgID string, limit int) ([]OrgEventRow, error) {
|
|
if limit < 1 || limit > 200 {
|
|
limit = 50
|
|
}
|
|
var out []OrgEventRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, workspace_id, event_type, actor_id, actor_name, request_id, old_name, new_name, at
|
|
FROM governance.org_events WHERE org_id = $1
|
|
ORDER BY at DESC, id DESC LIMIT $2`, orgID, limit); err != nil {
|
|
return nil, fmt.Errorf("list org events: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// keepActiveOwner refuses, inside tx, a change after which an org leaving owns
|
|
// org-wide (scoped to orgID when non-empty) has no other active owner.
|
|
func keepActiveOwner(ctx context.Context, tx *sqlx.Tx, leaving, orgID string) error {
|
|
var orgIDs []string
|
|
if err := tx.SelectContext(ctx, &orgIDs, `
|
|
SELECT org_id FROM governance.memberships
|
|
WHERE identity_id = $1 AND workspace_id IS NULL AND role = 'owner' AND ($2 = '' OR org_id = $2)`,
|
|
leaving, orgID); err != nil {
|
|
return err
|
|
}
|
|
if len(orgIDs) == 0 {
|
|
return nil
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `
|
|
SELECT 1 FROM governance.memberships
|
|
WHERE org_id = ANY($1::text[]) AND workspace_id IS NULL AND role = 'owner'
|
|
ORDER BY org_id, identity_id FOR UPDATE`, orgIDs); err != nil {
|
|
return err
|
|
}
|
|
var stranded int
|
|
if err := tx.GetContext(ctx, &stranded, `
|
|
SELECT count(*) FROM unnest($1::text[]) AS o(org_id)
|
|
WHERE NOT EXISTS (
|
|
SELECT 1 FROM governance.memberships m
|
|
JOIN governance.identities i ON i.id = m.identity_id
|
|
WHERE m.org_id = o.org_id AND m.workspace_id IS NULL AND m.role = 'owner'
|
|
AND i.lifecycle = 'active' AND m.identity_id <> $2
|
|
)`, orgIDs, leaving); err != nil {
|
|
return err
|
|
}
|
|
if stranded > 0 {
|
|
return ErrLastOwner
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// EnsureMembership grants or updates a membership role while preserving at least one active org owner.
|
|
func (s *Store) EnsureMembership(ctx context.Context, m MembershipRow) error {
|
|
if _, ok, err := s.GetOrg(ctx, m.OrgID); err != nil {
|
|
return err
|
|
} else if !ok {
|
|
return ErrNotFound
|
|
}
|
|
return s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
if (!m.WorkspaceID.Valid || m.WorkspaceID.String == "") && m.Role != "owner" {
|
|
if err := keepActiveOwner(ctx, tx, m.IdentityID, m.OrgID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
_, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.memberships (identity_id, org_id, workspace_id, role)
|
|
VALUES ($1, $2, NULLIF($3, ''), $4)
|
|
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO UPDATE SET role = EXCLUDED.role`,
|
|
m.IdentityID, m.OrgID, m.WorkspaceID.String, m.Role)
|
|
return err
|
|
})
|
|
}
|
|
|
|
// ListMembers returns an org's memberships joined with their identity display names.
|
|
func (s *Store) ListMembers(ctx context.Context, orgID string) ([]MemberRow, error) {
|
|
var out []MemberRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT m.identity_id, i.kind, i.display_name, m.workspace_id, m.role
|
|
FROM governance.memberships m
|
|
JOIN governance.identities i ON i.id = m.identity_id
|
|
WHERE m.org_id = $1
|
|
ORDER BY m.created_at, m.identity_id, m.workspace_id`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list members: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RemoveMembership revokes a membership while preserving at least one active org owner.
|
|
func (s *Store) RemoveMembership(ctx context.Context, identityID, orgID, workspaceID string) error {
|
|
return s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
if workspaceID == "" {
|
|
if err := keepActiveOwner(ctx, tx, identityID, orgID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
_, err := tx.ExecContext(ctx, `
|
|
DELETE FROM governance.memberships
|
|
WHERE identity_id = $1 AND org_id = $2 AND COALESCE(workspace_id, '') = $3`,
|
|
identityID, orgID, workspaceID)
|
|
return err
|
|
})
|
|
}
|
|
|
|
// ListMembershipsByIdentity returns all memberships held by identityID.
|
|
func (s *Store) ListMembershipsByIdentity(ctx context.Context, identityID string) ([]MembershipRow, error) {
|
|
var out []MembershipRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT identity_id, org_id, workspace_id, role, created_at
|
|
FROM governance.memberships WHERE identity_id = $1 ORDER BY created_at, org_id`, identityID); err != nil {
|
|
return nil, fmt.Errorf("list memberships: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ListOrgAgents returns every agent assignment in orgID.
|
|
func (s *Store) ListOrgAgents(ctx context.Context, orgID string) ([]AgentAssignmentRow, error) {
|
|
var out []AgentAssignmentRow
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT identity_id, org_id FROM governance.org_agents WHERE org_id = $1 ORDER BY identity_id`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list org agents: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// AssignAgent assigns an agent identity to orgID and ensures its developer membership.
|
|
func (s *Store) AssignAgent(ctx context.Context, identityID, orgID string) error {
|
|
if _, ok, err := s.GetOrg(ctx, orgID); err != nil {
|
|
return err
|
|
} else if !ok {
|
|
return ErrNotFound
|
|
}
|
|
return s.withTx(ctx, func(tx *sqlx.Tx) error {
|
|
if _, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.org_agents (identity_id, org_id) VALUES ($1, $2)
|
|
ON CONFLICT (identity_id) DO UPDATE SET org_id = EXCLUDED.org_id`, identityID, orgID); err != nil {
|
|
return err
|
|
}
|
|
_, err := tx.ExecContext(ctx, `
|
|
INSERT INTO governance.memberships (identity_id, org_id, role)
|
|
SELECT a.identity_id, a.org_id, 'developer' FROM governance.org_agents a
|
|
WHERE a.identity_id = $1
|
|
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING`, identityID)
|
|
return err
|
|
})
|
|
}
|
|
|
|
// EnsureAgentOrgMembership grants every assigned agent a developer membership if missing.
|
|
func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
|
|
_, err := s.db.ExecContext(ctx, `
|
|
INSERT INTO governance.memberships (identity_id, org_id, role)
|
|
SELECT a.identity_id, a.org_id, 'developer' FROM governance.org_agents a
|
|
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING`)
|
|
return err
|
|
}
|
|
|
|
// ResolveIdentityOrg resolves the org an identity serves, falling back to defaultOrgID.
|
|
func (s *Store) ResolveIdentityOrg(ctx context.Context, identityID, defaultOrgID string) (string, error) {
|
|
var resolved string
|
|
if err := s.db.GetContext(ctx, &resolved, `
|
|
SELECT COALESCE(
|
|
(SELECT a.org_id FROM governance.org_agents a WHERE a.identity_id = $1),
|
|
(SELECT m.org_id FROM governance.memberships m WHERE m.identity_id = $1
|
|
ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1),
|
|
$2
|
|
)::text AS org_id`, identityID, defaultOrgID); err != nil {
|
|
return "", fmt.Errorf("resolve identity org: %w", err)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
// ListOrgOwners returns the identity IDs holding an org-wide owner role.
|
|
func (s *Store) ListOrgOwners(ctx context.Context, orgID string) ([]string, error) {
|
|
var out []string
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT identity_id FROM governance.memberships
|
|
WHERE org_id = $1 AND workspace_id IS NULL AND role = 'owner'
|
|
ORDER BY identity_id`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list org owners: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|