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 class that bears on how much // autonomy it has. type event int const ( // approved: a person allowed one of the class's held actions. approved event = iota + 1 // denied: a person refused one of the class's held actions. denied // failed: an action of the class failed, or its outcome is unknown. failed // raiseApproved: a person approved the proposal to loosen the class. raiseApproved // raiseRefused: a person refused the proposal to loosen the class. raiseRefused ) // standing is what a class has earned: its level, the approvals counted since // it was last tightened or raised, and the level a raise waiting for an // answer would take it to (zero when none waits). type standing struct { level Level count int raiseTo Level } // after returns the standing the event leaves, and whether it earns a new // proposal to raise the class by one level once need approvals in a row have // counted. Autonomy is lost at once and earned only through a person: a // denial or failure never loosens a class, 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.raiseTo == 0 && next.count >= need && s.level > ActQuietly && s.level < Never { next.raiseTo = s.level - 1 propose = true } case denied, failed: next.level, next.count, next.raiseTo = max(s.level, ProposeAndWait), 0, 0 case raiseApproved: // A raise answers the level it was proposed from. A class that moved // since stays where it is. if s.raiseTo != 0 && s.level == s.raiseTo+1 { next.level, next.count = s.raiseTo, 0 } next.raiseTo = 0 case raiseRefused: next.count, next.raiseTo = 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 class levels aren't touched, so lifting the freeze restores them. func freezeCeiling(frozen, readOnly bool) Level { if frozen && !readOnly { return ProposeAndWait } return ActQuietly } // Raise is Archie's proposal to loosen a class by one level, with the // approvals that earned it. type Raise struct { ID uuid.UUID Class Class From, To Level Evidence []RaiseEvidence Deadline time.Time } // RaiseEvidence is one approval counted toward a raise. type RaiseEvidence struct { DecisionID uuid.UUID `json:"decision_id"` By string `json:"by"` At time.Time `json:"at"` } // Approved counts a person's approval of the held action decisionID, and // returns the raise it earns, if it does: need approvals in a row since the // class was last tightened. The raise waits until deadline for an answer. func (c *Classes) Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*Raise, error) { row, err := c.store.ClassOfDecision(ctx, c.orgID, decisionID) if errors.Is(err, store.ErrNoClass) { return nil, nil } if err != nil { return nil, err } var out *Raise err = c.store.InClass(ctx, c.orgID, row.ID, c.now().UTC(), func(t *store.ClassTx) error { if err := t.AddApproval(ctx, decisionID, by); err != nil { return err } out, err = c.apply(ctx, t, approved, need, deadline, "") return err }) return out, err } // Denied tightens the class of the held action decisionID that a person // refused. func (c *Classes) Denied(ctx context.Context, decisionID uuid.UUID) error { row, err := c.store.ClassOfDecision(ctx, c.orgID, decisionID) if errors.Is(err, store.ErrNoClass) { return nil } if err != nil { return err } return c.tighten(ctx, row.ID, "denied") } // Failed tightens the class of an action that failed or whose outcome is // unknown. func (c *Classes) Failed(ctx context.Context, class Class) error { row, err := c.store.ClassByKey(ctx, store.Class{ OrgID: c.orgID, Connector: class.Connector, Action: class.Action, TargetKind: class.TargetKind, Environment: class.Environment, }) if errors.Is(err, store.ErrNoClass) { return nil } if err != nil { return err } return c.tighten(ctx, row.ID, "failed") } func (c *Classes) tighten(ctx context.Context, id uuid.UUID, because string) error { return c.store.InClass(ctx, c.orgID, id, c.now().UTC(), func(t *store.ClassTx) error { _, err := c.apply(ctx, t, denied, 0, time.Time{}, because) return err }) } // AnswerRaise settles raise id with a person's answer, and raises the class // when it was approved and the class still stands where the proposal was made // from. It reports whether the class was raised. An answer to a raise that is // no longer waiting changes nothing. func (c *Classes) AnswerRaise(ctx context.Context, id uuid.UUID, answeredBy string, approve bool) (bool, error) { raise, err := c.store.RaiseByID(ctx, c.orgID, id) if err != nil { return false, err } var raised bool err = c.store.InClass(ctx, c.orgID, raise.ClassID, c.now().UTC(), func(t *store.ClassTx) error { _, pending, err := t.Count(ctx) if err != nil || pending == nil || pending.ID != id { return err } e := raiseRefused if approve { e = raiseApproved } before := t.Class.Level if _, err := c.apply(ctx, t, e, 0, time.Time{}, answeredBy); err != nil { return err } raised = approve && before == pending.FromLevel return nil }) return raised, err } // CancelRaise withdraws a raise whose request couldn't be asked, so the class // proposes it again at its next approval. func (c *Classes) CancelRaise(ctx context.Context, id uuid.UUID) error { return c.store.CancelRaise(ctx, c.orgID, id) } // apply moves the locked class through e and stores what changed. by is who // answered a raise, or why the class was tightened. func (c *Classes) apply(ctx context.Context, t *store.ClassTx, e event, need int, deadline time.Time, by string) (*Raise, 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, by); err != nil { return nil, err } if !propose { return nil, nil } return c.propose(ctx, t, cur.level, next.raiseTo, deadline) } // standingOf reads the locked class's standing, and the raise waiting for an // answer if one is. func standingOf(ctx context.Context, t *store.ClassTx) (standing, *store.Raise, error) { level, err := parseLevel(t.Class.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.raiseTo, 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.ClassTx, e event, cur, next standing, pending *store.Raise, by string) error { switch { case e == denied || e == failed: if err := t.Tighten(ctx, next.level.String(), by); 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.raiseTo == 0 { return t.CloseRaise(ctx, closedRaiseState(e, next.level != cur.level), closedBy(e, by)) } return nil } // closedRaiseState is how a raise ended. An approval that changed nothing, // because the class had moved since, doesn't count as approved. func closedRaiseState(e event, raised bool) string { switch { case e == raiseApproved && raised: return "approved" case e == raiseRefused: return "denied" } return "superseded" } func closedBy(e event, by string) string { if e == raiseApproved || e == raiseRefused { return by } return "" } func (c *Classes) propose(ctx context.Context, t *store.ClassTx, from, to Level, deadline time.Time) (*Raise, error) { evidence, err := t.Approvals(ctx) if err != nil { return nil, err } shown := make([]RaiseEvidence, len(evidence)) for i, a := range evidence { shown[i] = RaiseEvidence{DecisionID: a.DecisionID, By: a.By, At: a.At} } body, err := json.Marshal(shown) if err != nil { return nil, fmt.Errorf("encode evidence: %w", err) } r := &Raise{ ID: uuid.New(), From: from, To: to, Evidence: shown, Deadline: deadline.UTC(), Class: Class{ Connector: t.Class.Connector, Action: t.Class.Action, TargetKind: t.Class.TargetKind, Environment: t.Class.Environment, }, } if err := t.InsertRaise(ctx, store.Raise{ ID: r.ID, FromLevel: from.String(), ToLevel: to.String(), Evidence: body, Deadline: r.Deadline, }); err != nil { return nil, err } return r, nil }