390 lines
14 KiB
Go
390 lines
14 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
|
)
|
|
|
|
var (
|
|
_ org.Repository = (*Store)(nil)
|
|
_ org.Upgrader = (*Store)(nil)
|
|
)
|
|
|
|
// orgFromRow maps the generated org row to the domain org.
|
|
func orgFromRow(o postgresdb.Org) org.Org {
|
|
return org.Org{ID: org.OrgID(o.ID), Name: o.Name}
|
|
}
|
|
|
|
// CreateOrg inserts a new org, its default workspace and its owner in one
|
|
// transaction, so an org never exists without someone who can act in it.
|
|
// Re-creating an existing ID is ErrOrgExists.
|
|
func (s *Store) CreateOrg(ctx context.Context, value org.Org, owner identity.IdentityID) (org.Org, error) {
|
|
if err := value.Validate(); err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
membership := org.Membership{IdentityID: owner, OrgID: value.ID, Role: org.RoleOwner}
|
|
if err := membership.Validate(); err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
q := postgresdb.New(tx)
|
|
if err := q.InsertOrg(ctx, postgresdb.InsertOrgParams{ID: string(value.ID), Name: value.Name}); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return org.Org{}, fmt.Errorf("%w: %s", org.ErrOrgExists, value.ID)
|
|
}
|
|
return org.Org{}, err
|
|
}
|
|
if err := q.InsertWorkspace(ctx, postgresdb.InsertWorkspaceParams{
|
|
ID: string(org.DefaultWorkspaceID), OrgID: string(value.ID), Name: "Default",
|
|
}); err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
if err := q.EnsureMembership(ctx, postgresdb.EnsureMembershipParams{
|
|
IdentityID: string(owner), OrgID: string(value.ID), Role: string(org.RoleOwner),
|
|
}); err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
return value, tx.Commit(ctx)
|
|
}
|
|
|
|
// GetOrg returns one org by ID, or ErrOrgNotFound.
|
|
func (s *Store) GetOrg(ctx context.Context, id org.OrgID) (org.Org, error) {
|
|
o, err := s.queries().GetOrg(ctx, string(id))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return org.Org{}, org.ErrOrgNotFound
|
|
}
|
|
if err != nil {
|
|
return org.Org{}, err
|
|
}
|
|
return orgFromRow(o), nil
|
|
}
|
|
|
|
// ListOrgs returns every org, oldest first.
|
|
func (s *Store) ListOrgs(ctx context.Context) ([]org.Org, error) {
|
|
rows, err := s.queries().ListOrgs(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]org.Org, 0, len(rows))
|
|
for _, r := range rows {
|
|
out = append(out, orgFromRow(r))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// CreateWorkspace inserts a workspace into an existing org; an unknown org is
|
|
// ErrOrgNotFound.
|
|
func (s *Store) CreateWorkspace(ctx context.Context, value org.Workspace) (org.Workspace, error) {
|
|
if err := value.Validate(); err != nil {
|
|
return org.Workspace{}, err
|
|
}
|
|
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
|
|
return org.Workspace{}, err
|
|
}
|
|
if err := s.queries().InsertWorkspace(ctx, postgresdb.InsertWorkspaceParams{
|
|
ID: string(value.ID), OrgID: string(value.OrgID),
|
|
Name: value.Name, Environment: value.Environment,
|
|
}); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return org.Workspace{}, fmt.Errorf("%w: %s/%s", org.ErrWorkspaceExists, value.OrgID, value.ID)
|
|
}
|
|
return org.Workspace{}, err
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
// workspaceFromRow maps the generated workspace row to the domain workspace.
|
|
func workspaceFromRow(w postgresdb.Workspace) org.Workspace {
|
|
return org.Workspace{
|
|
ID: org.WorkspaceID(w.ID), OrgID: org.OrgID(w.OrgID),
|
|
Name: w.Name, Environment: w.Environment,
|
|
}
|
|
}
|
|
|
|
// ListWorkspaces returns an org's workspaces, oldest first.
|
|
func (s *Store) ListWorkspaces(ctx context.Context, id org.OrgID) ([]org.Workspace, error) {
|
|
rows, err := s.queries().ListWorkspaces(ctx, string(id))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]org.Workspace, 0, len(rows))
|
|
for _, r := range rows {
|
|
out = append(out, workspaceFromRow(r))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// EnsureMembership grants an identity a role in an org, or in one workspace
|
|
// of it; an identical existing membership is not an error.
|
|
func (s *Store) EnsureMembership(ctx context.Context, value org.Membership) error {
|
|
if err := value.Validate(); err != nil {
|
|
return err
|
|
}
|
|
var workspace pgtype.Text
|
|
if value.WorkspaceID != "" {
|
|
workspace = pgtype.Text{String: string(value.WorkspaceID), Valid: true}
|
|
}
|
|
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
|
|
return err
|
|
}
|
|
params := postgresdb.EnsureMembershipParams{
|
|
IdentityID: string(value.IdentityID),
|
|
OrgID: string(value.OrgID),
|
|
WorkspaceID: workspace,
|
|
Role: string(value.Role),
|
|
}
|
|
if value.WorkspaceID != "" || value.Role == org.RoleOwner {
|
|
return s.queries().EnsureMembership(ctx, params)
|
|
}
|
|
return s.guardOwners(ctx, string(value.IdentityID), string(value.OrgID), func(q *postgresdb.Queries) error {
|
|
return q.EnsureMembership(ctx, params)
|
|
})
|
|
}
|
|
|
|
// AssignAgent records the one org an agent or service identity serves,
|
|
// replacing any prior assignment for that identity.
|
|
func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) error {
|
|
if err := value.Validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.GetOrg(ctx, value.OrgID); err != nil {
|
|
return err
|
|
}
|
|
return s.queries().UpsertAgentAssignment(ctx, postgresdb.UpsertAgentAssignmentParams{
|
|
IdentityID: string(value.IdentityID), OrgID: string(value.OrgID),
|
|
})
|
|
}
|
|
|
|
// ListMembers returns an org's memberships with the identity each names.
|
|
func (s *Store) ListMembers(ctx context.Context, id org.OrgID) ([]org.Member, error) {
|
|
rows, err := s.queries().ListMembers(ctx, string(id))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]org.Member, 0, len(rows))
|
|
for _, r := range rows {
|
|
var ws org.WorkspaceID
|
|
if r.WorkspaceID.Valid {
|
|
ws = org.WorkspaceID(r.WorkspaceID.String)
|
|
}
|
|
out = append(out, org.Member{
|
|
IdentityID: identity.IdentityID(r.IdentityID), Kind: identity.Kind(r.Kind),
|
|
DisplayName: r.DisplayName, WorkspaceID: ws, Role: org.Role(r.Role),
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RemoveMembership revokes one membership; a missing one is not an error.
|
|
func (s *Store) RemoveMembership(ctx context.Context, value org.Membership) error {
|
|
if value.IdentityID == "" || value.OrgID == "" {
|
|
return fmt.Errorf("%w: identity and org are required", org.ErrInvalidMembership)
|
|
}
|
|
params := postgresdb.RemoveMembershipParams{
|
|
IdentityID: string(value.IdentityID), OrgID: string(value.OrgID), WorkspaceID: string(value.WorkspaceID),
|
|
}
|
|
if value.WorkspaceID != "" {
|
|
return s.queries().RemoveMembership(ctx, params)
|
|
}
|
|
return s.guardOwners(ctx, string(value.IdentityID), string(value.OrgID), func(q *postgresdb.Queries) error {
|
|
return q.RemoveMembership(ctx, params)
|
|
})
|
|
}
|
|
|
|
// ListOrgAgents returns the agent and service identities assigned to an org.
|
|
func (s *Store) ListOrgAgents(ctx context.Context, id org.OrgID) ([]org.AgentAssignment, error) {
|
|
rows, err := s.queries().ListOrgAgents(ctx, string(id))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]org.AgentAssignment, 0, len(rows))
|
|
for _, r := range rows {
|
|
out = append(out, org.AgentAssignment{IdentityID: identity.IdentityID(r.IdentityID), OrgID: org.OrgID(r.OrgID)})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// EnsureAgentOrgMembership grants every agent identity the shipped developer
|
|
// role in the org it serves. It runs at the State Store's boot, after the
|
|
// default-org upgrade, so dispatch's chain has a principal to evaluate.
|
|
// Idempotent: an existing membership (any role) is left alone.
|
|
func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error {
|
|
return s.queries().EnsureAgentOrgMembership(ctx)
|
|
}
|
|
|
|
// PrincipalFor assembles the access principal for one identity: the org it
|
|
// serves and its memberships (internal/domain/access). An identity in no org
|
|
// is the default org with no role, which the shipped role policies never
|
|
// permit.
|
|
func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) {
|
|
resolved, err := s.OrgForIdentity(ctx, id)
|
|
if err != nil {
|
|
return access.Principal{}, err
|
|
}
|
|
rows, err := s.queries().ListMembershipsByIdentity(ctx, string(id))
|
|
if err != nil {
|
|
return access.Principal{}, err
|
|
}
|
|
memberships := make([]org.Membership, 0, len(rows))
|
|
for _, r := range rows {
|
|
var ws org.WorkspaceID
|
|
if r.WorkspaceID.Valid {
|
|
ws = org.WorkspaceID(r.WorkspaceID.String)
|
|
}
|
|
memberships = append(memberships, org.Membership{
|
|
IdentityID: id,
|
|
OrgID: org.OrgID(r.OrgID),
|
|
WorkspaceID: ws,
|
|
Role: org.Role(r.Role),
|
|
})
|
|
}
|
|
workspaces, err := s.ListWorkspaces(ctx, resolved)
|
|
if err != nil {
|
|
return access.Principal{}, err
|
|
}
|
|
return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships, Workspaces: workspaces}, nil
|
|
}
|
|
|
|
// OrgForIdentity returns the org an identity serves: the assigned org for an
|
|
// agent, the org of one of its memberships for a person, and the default org
|
|
// for an identity in no org.
|
|
func (s *Store) OrgForIdentity(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
|
|
resolved, err := s.queries().ResolveIdentityOrg(ctx, string(id))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return org.OrgID(resolved), nil
|
|
}
|
|
|
|
// UpgradeDefaultOrg runs the resumable default org/workspace upgrade: the
|
|
// State Store phase first, the event-capture phase second, each in one
|
|
// transaction with its ledger row so a phase is either recorded or entirely
|
|
// absent, and each skipped on a later start once recorded.
|
|
func (s *Store) UpgradeDefaultOrg(ctx context.Context) error {
|
|
type phase struct {
|
|
name string
|
|
stamps []func(context.Context, *postgresdb.Queries) (int64, error)
|
|
}
|
|
phases := []phase{
|
|
{name: "state_store", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampStateStoreTasks(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampStateStoreEvents(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
|
|
return q.StampStateStoreTransitions(ctx)
|
|
},
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
|
|
return q.StampStateStoreResources(ctx)
|
|
},
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
|
|
return q.StampStateStoreResourceHistory(ctx)
|
|
},
|
|
}},
|
|
{name: "edastore", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreBindings(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreMappings(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreCaptures(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreSources(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreEventTypes(ctx) },
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) { return q.StampEdastoreToolCalls(ctx) },
|
|
}},
|
|
// The operator phase runs last: it needs the org the state_store phase
|
|
// creates, and gives the dashboard a person to act as where none exists.
|
|
{name: "operator", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
|
|
ensureOrgOperator,
|
|
}},
|
|
// Its own phase so installs that recorded the operator phase before
|
|
// the agent existed still get it. The final assignment below puts it
|
|
// in org-sys, and every agent's developer membership grants run.
|
|
{name: "agent", stamps: []func(context.Context, *postgresdb.Queries) (int64, error){
|
|
func(ctx context.Context, q *postgresdb.Queries) (int64, error) {
|
|
return q.EnsureOrgAgentIdentity(ctx, string(identity.AgentID()))
|
|
},
|
|
}},
|
|
}
|
|
for _, p := range phases {
|
|
if _, err := s.queries().GetOrgUpgradePhase(ctx, p.name); err == nil {
|
|
continue // recorded: the phase committed on an earlier start
|
|
} else if !errors.Is(err, pgx.ErrNoRows) {
|
|
return err
|
|
}
|
|
if err := s.runUpgradePhase(ctx, p.name, p.stamps); err != nil {
|
|
return fmt.Errorf("org upgrade phase %s: %w", p.name, err)
|
|
}
|
|
}
|
|
// Bootstrapped identities appear after the phases are recorded (a name
|
|
// added to config later), so assignment runs on every start; an
|
|
// identity already in an org keeps it.
|
|
return s.queries().AssignDefaultOrgIdentities(ctx)
|
|
}
|
|
|
|
// ensureOrgOperator creates the dashboard's operator person as org-sys's owner
|
|
// when no person owns it yet. Both writes re-check that condition, so a
|
|
// re-run leaves an existing person owner alone and never adds a second.
|
|
func ensureOrgOperator(ctx context.Context, q *postgresdb.Queries) (int64, error) {
|
|
params := postgresdb.EnsureOrgOperatorIdentityParams{
|
|
ID: string(identity.OperatorID()), OrgID: string(org.DefaultOrgID),
|
|
}
|
|
if _, err := q.EnsureOrgOperatorIdentity(ctx, params); err != nil {
|
|
return 0, err
|
|
}
|
|
return q.EnsureOrgOperatorMembership(ctx, postgresdb.EnsureOrgOperatorMembershipParams{
|
|
IdentityID: params.ID, OrgID: params.OrgID,
|
|
})
|
|
}
|
|
|
|
// runUpgradePhase stamps one phase's tables and records its ledger row in one
|
|
// transaction. An interrupted phase reruns from the start.
|
|
func (s *Store) runUpgradePhase(ctx context.Context, name string, stamps []func(context.Context, *postgresdb.Queries) (int64, error)) error {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
q := postgresdb.New(tx)
|
|
|
|
if err := q.EnsureDefaultOrg(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := q.EnsureDefaultWorkspace(ctx); err != nil {
|
|
return err
|
|
}
|
|
if err := q.AssignDefaultOrgIdentities(ctx); err != nil {
|
|
return err
|
|
}
|
|
for _, stamp := range stamps {
|
|
if _, err := stamp(ctx, q); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := q.InsertOrgUpgradePhase(ctx, name); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
// OrgOwners returns the identities holding the org-wide owner role.
|
|
func (s *Store) OrgOwners(ctx context.Context, orgID org.OrgID) ([]identity.IdentityID, error) {
|
|
rows, err := s.queries().ListOrgOwners(ctx, string(orgID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("store: list org owners: %w", err)
|
|
}
|
|
out := make([]identity.IdentityID, 0, len(rows))
|
|
for _, id := range rows {
|
|
out = append(out, identity.IdentityID(id))
|
|
}
|
|
return out, nil
|
|
}
|