Files

314 lines
10 KiB
Go

package judgement
import (
"context"
json "encoding/json/v2"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// event is something that happened to an action type that bears on how much
// autonomy it has.
type event int
const (
// approved: a person allowed one of the action type's held actions.
approved event = iota + 1
// denied: a person refused one of the action type's held actions.
denied
// failed: an action of the action type failed, or its outcome is unknown.
failed
// proposalApproved: a person approved the proposal to loosen the action type.
proposalApproved
// proposalRefused: a person refused the proposal to loosen the action type.
proposalRefused
)
// standing is the autonomy an action type has earned: its level, the approvals
// counted since its level last changed, and the level a pending autonomy
// proposal would set (zero when no proposal is pending).
type standing struct {
level Level
count int
proposedLevel Level
}
// after returns the standing after event e, and whether to propose loosening
// the action type by one level because need approvals in a row have been
// counted. Autonomy is lost at once and earned only through a person: a
// denial or failure never loosens an action type, and approvals never loosen it
// themselves.
func (s standing) after(e event, need int) (next standing, propose bool) {
next = s
switch e {
case approved:
next.count++
if s.proposedLevel == 0 && next.count >= need && s.level > ActQuietly && s.level < Never {
next.proposedLevel = s.level - 1
propose = true
}
case denied, failed:
next.level, next.count, next.proposedLevel = max(s.level, ProposeAndWait), 0, 0
case proposalApproved:
// An autonomy proposal answers the level it was proposed from. An action type that moved
// since stays where it is.
if s.proposedLevel != 0 && s.level == s.proposedLevel+1 {
next.level, next.count = s.proposedLevel, 0
}
next.proposedLevel = 0
case proposalRefused:
next.count, next.proposedLevel = 0, 0
}
return next, propose
}
// freezeCeiling is the ceiling a freeze sets: a frozen organisation holds
// every action that changes something at propose and wait, and leaves reading
// alone. The action type levels aren't touched, so lifting the freeze restores them.
func freezeCeiling(frozen, readOnly bool) Level {
if frozen && !readOnly {
return ProposeAndWait
}
return ActQuietly
}
// AutonomyProposal is Archie's proposal to loosen an action type by one level, with the
// approvals that earned it.
type AutonomyProposal struct {
ID uuid.UUID
ActionTypeID uuid.UUID
ActionType ActionType
From, To Level
Evidence []ProposalEvidence
Deadline time.Time
}
// ProposalEvidence is one approval counted toward an autonomy proposal.
type ProposalEvidence struct {
DecisionID uuid.UUID `json:"decision_id"`
By string `json:"by"`
ByID string `json:"by_id,omitzero"`
At time.Time `json:"at"`
}
// Approved counts a person's approval of the held action decisionID, and
// returns the autonomy proposal it earns, if it does: need approvals in a row since the
// action type was last tightened. The autonomy proposal waits until deadline for an answer.
func (c *ActionTypes) Approved(ctx context.Context, decisionID uuid.UUID, who Answerer, need int, deadline time.Time) (*AutonomyProposal, error) {
row, err := c.store.ActionTypeOfDecision(ctx, c.orgID, decisionID)
if errors.Is(err, store.ErrNoActionType) {
return nil, nil
}
if err != nil {
return nil, err
}
var out *AutonomyProposal
err = c.store.InActionType(ctx, c.orgID, row.ID, c.now().UTC(), func(t *store.ActionTypeTx) error {
if err := t.AddApproval(ctx, decisionID, who.Name, who.ID); err != nil {
return err
}
out, err = c.apply(ctx, t, approved, need, deadline, cause{})
return err
})
return out, err
}
// Denied tightens the action type of the held action decisionID that a person
// refused.
func (c *ActionTypes) Denied(ctx context.Context, decisionID uuid.UUID) error {
row, err := c.store.ActionTypeOfDecision(ctx, c.orgID, decisionID)
if errors.Is(err, store.ErrNoActionType) {
return nil
}
if err != nil {
return err
}
return c.tighten(ctx, row.ID, "denied")
}
// Failed tightens the action type of an action that failed or whose outcome is
// unknown.
func (c *ActionTypes) Failed(ctx context.Context, actionType ActionType) error {
row, err := c.store.ActionTypeByKey(ctx, store.ActionType{
OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action,
TargetKind: actionType.TargetKind, Environment: actionType.Environment,
})
if errors.Is(err, store.ErrNoActionType) {
return nil
}
if err != nil {
return err
}
return c.tighten(ctx, row.ID, "failed")
}
func (c *ActionTypes) tighten(ctx context.Context, id uuid.UUID, because string) error {
return c.store.InActionType(ctx, c.orgID, id, c.now().UTC(), func(t *store.ActionTypeTx) error {
_, err := c.apply(ctx, t, denied, 0, time.Time{}, cause{because: because})
return err
})
}
// AnswerProposal settles autonomy proposal id with a person's answer, and loosens the action type
// when it was approved and the action type still stands where the proposal was made
// from. It reports whether the action type was loosened. An answer to an autonomy proposal that is
// no longer waiting changes nothing.
func (c *ActionTypes) AnswerProposal(ctx context.Context, id uuid.UUID, who Answerer, approve bool) (bool, error) {
proposal, err := c.store.ProposalByID(ctx, c.orgID, id)
if err != nil {
return false, err
}
var loosened bool
err = c.store.InActionType(ctx, c.orgID, proposal.ActionTypeID, c.now().UTC(), func(t *store.ActionTypeTx) error {
_, pending, err := t.Count(ctx)
if err != nil || pending == nil || pending.ID != id {
return err
}
e := proposalRefused
if approve {
e = proposalApproved
}
before := t.ActionType.Level
if _, err := c.apply(ctx, t, e, 0, time.Time{}, cause{answerer: who}); err != nil {
return err
}
loosened = approve && before == pending.FromLevel
return nil
})
return loosened, err
}
// CancelProposal withdraws an autonomy proposal whose request couldn't be asked, so the action type
// proposes it again at its next approval.
func (c *ActionTypes) CancelProposal(ctx context.Context, id uuid.UUID) error {
return c.store.CancelProposal(ctx, c.orgID, id)
}
// Answerer is the account that answered an autonomy proposal: its identity ID,
// and its display name at the time of the answer.
type Answerer struct {
ID string
Name string
}
// cause records who answered an autonomy proposal, or why an action type was
// tightened.
type cause struct {
answerer Answerer
because string
}
// apply moves the locked action type through e and stores what changed.
func (c *ActionTypes) apply(ctx context.Context, t *store.ActionTypeTx, e event, need int, deadline time.Time, why cause) (*AutonomyProposal, error) {
cur, pending, err := standingOf(ctx, t)
if err != nil {
return nil, err
}
next, propose := cur.after(e, need)
if err := write(ctx, t, e, cur, next, pending, why); err != nil {
return nil, err
}
if !propose {
return nil, nil
}
return c.propose(ctx, t, cur.level, next.proposedLevel, deadline)
}
// standingOf reads the locked action type's standing, and the autonomy proposal waiting for an
// answer if one is.
func standingOf(ctx context.Context, t *store.ActionTypeTx) (standing, *store.AutonomyProposal, error) {
level, err := parseLevel(t.ActionType.Level)
if err != nil {
return standing{}, nil, err
}
count, pending, err := t.Count(ctx)
if err != nil {
return standing{}, nil, err
}
s := standing{level: level, count: count}
if pending != nil {
if s.proposedLevel, err = parseLevel(pending.ToLevel); err != nil {
return standing{}, nil, err
}
}
return s, pending, nil
}
// write stores the difference between two standings.
func write(ctx context.Context, t *store.ActionTypeTx, e event, cur, next standing, pending *store.AutonomyProposal, why cause) error {
switch {
case e == denied || e == failed:
if err := t.Tighten(ctx, next.level.String(), why.because); err != nil {
return err
}
case next.level != cur.level:
if err := t.SetLevel(ctx, next.level.String()); err != nil {
return err
}
}
if next.count == 0 && cur.count > 0 {
if err := t.ClearCount(ctx); err != nil {
return err
}
}
if pending != nil && next.proposedLevel == 0 {
who := closedBy(e, why.answerer)
return t.CloseProposal(ctx, closedProposalState(e, next.level != cur.level), who.Name, who.ID)
}
return nil
}
// closedProposalState is how an autonomy proposal ended. An approval that changed nothing,
// because the action type had moved since, doesn't count as approved.
func closedProposalState(e event, loosened bool) string {
switch {
case e == proposalApproved && loosened:
return "approved"
case e == proposalRefused:
return "denied"
}
return "superseded"
}
// closedBy returns the account that answered a proposal, or an empty Answerer
// when the proposal was withdrawn.
func closedBy(e event, who Answerer) Answerer {
if e == proposalApproved || e == proposalRefused {
return who
}
return Answerer{}
}
func (c *ActionTypes) propose(ctx context.Context, t *store.ActionTypeTx, from, to Level, deadline time.Time) (*AutonomyProposal, error) {
evidence, err := t.Approvals(ctx)
if err != nil {
return nil, err
}
shown := make([]ProposalEvidence, len(evidence))
for i, a := range evidence {
shown[i] = ProposalEvidence{DecisionID: a.DecisionID, By: a.By, ByID: a.ByID, At: a.At}
}
body, err := json.Marshal(shown)
if err != nil {
return nil, fmt.Errorf("encode evidence: %w", err)
}
r := &AutonomyProposal{
ID: uuid.New(), ActionTypeID: t.ActionType.ID, From: from, To: to, Evidence: shown, Deadline: deadline.UTC(),
ActionType: ActionType{
Connector: t.ActionType.Connector, Action: t.ActionType.Action,
TargetKind: t.ActionType.TargetKind, Environment: t.ActionType.Environment,
},
}
if err := t.InsertProposal(ctx, store.AutonomyProposal{
ID: r.ID, FromLevel: from.String(), ToLevel: to.String(), Evidence: body, Deadline: r.Deadline,
}); err != nil {
return nil, err
}
return r, nil
}