Files
archie/internal/infrastructure/postgres/owners_guard.go
T

65 lines
2.0 KiB
Go

package postgres
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// keepActiveOwner refuses, inside tx, a change after which an org leaving owns
// org-wide (only orgID, when it is set) has no other active owner. The owner rows are locked first, so two
// owners suspending or removing each other concurrently serialise and the
// second sees the first's change.
func keepActiveOwner(ctx context.Context, tx pgx.Tx, leaving, orgID string) error {
rows, err := tx.Query(ctx, `SELECT org_id FROM memberships
WHERE identity_id = $1 AND workspace_id IS NULL AND role = 'owner' AND ($2 = '' OR org_id = $2)`, leaving, orgID)
if err != nil {
return err
}
orgIDs, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return err
}
if len(orgIDs) == 0 {
return nil
}
if _, err := tx.Exec(ctx, `SELECT 1 FROM memberships
WHERE org_id = ANY($1) AND workspace_id IS NULL AND role = 'owner'
ORDER BY org_id, identity_id FOR UPDATE`, orgIDs); err != nil {
return err
}
var stranded int
err = tx.QueryRow(ctx, `SELECT count(*) FROM unnest($1::text[]) AS o(org_id)
WHERE NOT EXISTS (
SELECT 1 FROM memberships m JOIN 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).Scan(&stranded)
if err != nil {
return err
}
if stranded > 0 {
return org.ErrLastOwner
}
return nil
}
// guardOwners runs fn in a transaction after keepActiveOwner allows leaving
// to stop owning orgID.
func (s *Store) guardOwners(ctx context.Context, leaving, orgID string, fn func(*postgresdb.Queries) error) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if err := keepActiveOwner(ctx, tx, leaving, orgID); err != nil {
return err
}
if err := fn(postgresdb.New(tx)); err != nil {
return err
}
return tx.Commit(ctx)
}