Files

254 lines
10 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// ErrNoProposal means no autonomy proposal has that id.
var ErrNoProposal = errors.New("no such autonomy proposal")
// AutonomyProposal is a proposal to loosen an action type by one level.
type AutonomyProposal struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
ActionTypeID uuid.UUID `db:"action_type_id"`
FromLevel string `db:"from_level"`
ToLevel string `db:"to_level"`
Evidence []byte `db:"evidence"`
State string `db:"state"`
Deadline time.Time `db:"deadline"`
ProposedAt time.Time `db:"proposed_at"`
AnsweredBy sql.NullString `db:"answered_by"`
// AnsweredByID is the identity ID of the account that answered; AnsweredBy
// is its display name at the time.
AnsweredByID sql.NullString `db:"answered_by_id"`
AnsweredAt sql.NullTime `db:"answered_at"`
}
const proposalColumns = `id, org_id, action_type_id, from_level, to_level, evidence, state, deadline, proposed_at, answered_by, answered_by_id, answered_at`
// ActionTypeOfDecision returns the action type a decision belongs to.
func (s *Store) ActionTypeOfDecision(ctx context.Context, orgID string, decisionID uuid.UUID) (ActionType, error) {
var out ActionType
err := s.db.GetContext(ctx, &out, `
SELECT c.id, c.org_id, c.connector, c.action, c.target_kind, c.environment, c.read_only, c.level,
c.created_at, c.reset_at, c.tightened_at, c.tightened_because
FROM judgement.decisions d
JOIN judgement.action_types c ON c.org_id = d.org_id AND c.connector = d.connector AND c.action = d.action
AND c.target_kind = d.target_kind AND c.environment = d.environment
WHERE d.org_id = $1 AND d.id = $2`, orgID, decisionID)
if errors.Is(err, sql.ErrNoRows) {
return ActionType{}, ErrNoActionType
}
if err != nil {
return ActionType{}, fmt.Errorf("read action type of decision: %w", err)
}
return out, nil
}
// ActionTypeByKey returns the action type with c's connector, action, target
// kind and environment.
func (s *Store) ActionTypeByKey(ctx context.Context, c ActionType) (ActionType, error) {
var out ActionType
err := s.db.GetContext(ctx, &out, `
SELECT `+actionTypeColumns+` FROM judgement.action_types
WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5`,
c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment)
if errors.Is(err, sql.ErrNoRows) {
return ActionType{}, ErrNoActionType
}
if err != nil {
return ActionType{}, fmt.Errorf("read action type: %w", err)
}
return out, nil
}
// ProposalByID returns one autonomy proposal.
func (s *Store) ProposalByID(ctx context.Context, orgID string, id uuid.UUID) (AutonomyProposal, error) {
var out AutonomyProposal
err := s.db.GetContext(ctx, &out, `SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return AutonomyProposal{}, ErrNoProposal
}
if err != nil {
return AutonomyProposal{}, fmt.Errorf("read autonomy proposal: %w", err)
}
return out, nil
}
// ActionTypeProposals returns an action type's autonomy proposals, newest first.
func (s *Store) ActionTypeProposals(ctx context.Context, id uuid.UUID) ([]AutonomyProposal, error) {
var out []AutonomyProposal
if err := s.db.SelectContext(ctx, &out, `
SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE action_type_id = $1 ORDER BY proposed_at DESC, id`, id); err != nil {
return nil, fmt.Errorf("list action type autonomy proposals: %w", err)
}
return out, nil
}
// ActionTypeCount returns how many approvals an action type has counted, for the action type
// view.
func (s *Store) ActionTypeCount(ctx context.Context, id uuid.UUID) (int, error) {
var n int
if err := s.db.GetContext(ctx, &n, `SELECT count(*) FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted`, id); err != nil {
return 0, fmt.Errorf("count approvals: %w", err)
}
return n, nil
}
// ActionTypeTx is one action type held for update. Everything done through it commits
// together, so two answers arriving at once see each other's count.
type ActionTypeTx struct {
tx *sqlx.Tx
now time.Time
ActionType ActionType
}
// InActionType runs fn with the action type locked. An autonomy proposal nobody answered by its
// deadline is expired first, and its count restarts, so an action type that wasn't
// raised is asked again only after earning it again.
func (s *Store) InActionType(ctx context.Context, orgID string, id uuid.UUID, now time.Time, fn func(*ActionTypeTx) error) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("action type: %w", err)
}
defer func() { _ = tx.Rollback() }()
t := &ActionTypeTx{tx: tx, now: now}
err = tx.GetContext(ctx, &t.ActionType, `SELECT `+actionTypeColumns+` FROM judgement.action_types WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return ErrNoActionType
}
if err != nil {
return fmt.Errorf("lock action type: %w", err)
}
res, err := tx.ExecContext(ctx, `
UPDATE judgement.autonomy_proposals SET state = 'expired', answered_at = $2
WHERE action_type_id = $1 AND state = 'pending' AND deadline <= $2`, id, now)
if err != nil {
return fmt.Errorf("expire autonomy proposal: %w", err)
}
if n, _ := res.RowsAffected(); n > 0 {
if err := t.ClearCount(ctx); err != nil {
return err
}
}
if err := fn(t); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("action type: %w", err)
}
return nil
}
// Count returns how many approvals count toward an autonomy proposal, and the autonomy proposal waiting
// for an answer, if one is.
func (t *ActionTypeTx) Count(ctx context.Context) (int, *AutonomyProposal, error) {
var n int
if err := t.tx.GetContext(ctx, &n, `SELECT count(*) FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted`, t.ActionType.ID); err != nil {
return 0, nil, fmt.Errorf("count approvals: %w", err)
}
var r AutonomyProposal
err := t.tx.GetContext(ctx, &r, `SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE action_type_id = $1 AND state = 'pending'`, t.ActionType.ID)
if errors.Is(err, sql.ErrNoRows) {
return n, nil, nil
}
if err != nil {
return 0, nil, fmt.Errorf("read pending autonomy proposal: %w", err)
}
return n, &r, nil
}
// AddApproval counts one approved decision. A decision counts once.
func (t *ActionTypeTx) AddApproval(ctx context.Context, decisionID uuid.UUID, by, byID string) error {
if _, err := t.tx.ExecContext(ctx, `
INSERT INTO judgement.action_type_approvals (id, org_id, action_type_id, decision_id, by, by_id, at)
VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (decision_id) DO NOTHING`,
uuid.New(), t.ActionType.OrgID, t.ActionType.ID, decisionID, by, byID, t.now); err != nil {
return fmt.Errorf("record approval: %w", err)
}
return nil
}
// Approval is one counted approval, the evidence for an autonomy proposal.
type Approval struct {
DecisionID uuid.UUID `db:"decision_id" json:"decision_id"`
By string `db:"by" json:"by"`
ByID string `db:"by_id" json:"by_id,omitzero"`
At time.Time `db:"at" json:"at"`
}
// Approvals returns the approvals that count, oldest first.
func (t *ActionTypeTx) Approvals(ctx context.Context) ([]Approval, error) {
var out []Approval
if err := t.tx.SelectContext(ctx, &out, `
SELECT decision_id, by, by_id, at FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted ORDER BY at, id`, t.ActionType.ID); err != nil {
return nil, fmt.Errorf("list approvals: %w", err)
}
return out, nil
}
// ClearCount stops every approval counting.
func (t *ActionTypeTx) ClearCount(ctx context.Context) error {
if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.action_type_approvals SET counted = false WHERE action_type_id = $1 AND counted`, t.ActionType.ID); err != nil {
return fmt.Errorf("clear approvals: %w", err)
}
return nil
}
// SetLevel sets the action type's level.
func (t *ActionTypeTx) SetLevel(ctx context.Context, level string) error {
if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.action_types SET level = $2 WHERE id = $1`, t.ActionType.ID, level); err != nil {
return fmt.Errorf("set level: %w", err)
}
return nil
}
// Tighten records that the action type lost autonomy, and why.
func (t *ActionTypeTx) Tighten(ctx context.Context, level, because string) error {
if _, err := t.tx.ExecContext(ctx, `
UPDATE judgement.action_types SET level = $2, tightened_at = $3, tightened_because = $4 WHERE id = $1`,
t.ActionType.ID, level, t.now, because); err != nil {
return fmt.Errorf("tighten action type: %w", err)
}
return nil
}
// CloseProposal settles the action type's pending autonomy proposal.
func (t *ActionTypeTx) CloseProposal(ctx context.Context, state, byName, byID string) error {
if _, err := t.tx.ExecContext(ctx, `
UPDATE judgement.autonomy_proposals
SET state = $2, answered_by = nullif($3, ''), answered_by_id = nullif($4, ''), answered_at = $5
WHERE action_type_id = $1 AND state = 'pending'`, t.ActionType.ID, state, byName, byID, t.now); err != nil {
return fmt.Errorf("close autonomy proposal: %w", err)
}
return nil
}
// InsertProposal records a proposal.
func (t *ActionTypeTx) InsertProposal(ctx context.Context, r AutonomyProposal) error {
if _, err := t.tx.ExecContext(ctx, `
INSERT INTO judgement.autonomy_proposals (id, org_id, action_type_id, from_level, to_level, evidence, state, deadline, proposed_at)
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8)`,
r.ID, t.ActionType.OrgID, t.ActionType.ID, r.FromLevel, r.ToLevel, r.Evidence, r.Deadline, t.now); err != nil {
return fmt.Errorf("record autonomy proposal: %w", err)
}
return nil
}
// CancelProposal withdraws a pending autonomy proposal whose request couldn't be asked.
func (s *Store) CancelProposal(ctx context.Context, orgID string, id uuid.UUID) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE judgement.autonomy_proposals SET state = 'superseded' WHERE org_id = $1 AND id = $2 AND state = 'pending'`, orgID, id); err != nil {
return fmt.Errorf("cancel autonomy proposal: %w", err)
}
return nil
}