package proposals import ( "errors" "fmt" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/proposals/internal/store" "github.com/samcharles93/archie-core/modules/runs" ) // ErrNotBound means an approved proposal's action is not the action that was // judged and shown to the person who approved. var ErrNotBound = errors.New("the action is not the one that was approved") // bind returns what an approved proposal allows its actions to run as. An // approval covers an action only when the action stored with the proposal is // the one its decision judged: same decision, and an input that still hashes to // the digest both carry. An action that was changed after it was shown, or // whose decision refuses it, gets no approval, and so none of the proposal's // actions run. func bind(p store.Proposal, actions []store.Action, decisions []judgement.Decision) ([]runs.ApprovedAction, error) { if p.State != StateApproved || !p.AnsweredAt.Valid || !p.AnsweredByID.Valid { return nil, fmt.Errorf("%w: the proposal is %s", ErrNotBound, p.State) } byID := make(map[string]judgement.Decision, len(decisions)) for _, d := range decisions { byID[d.ID.String()] = d } out := make([]runs.ApprovedAction, 0, len(actions)) for _, a := range actions { d, ok := byID[a.DecisionID.String()] switch { case !ok: return nil, fmt.Errorf("%w: action %d has no judgement", ErrNotBound, a.Seq) case d.Level == judgement.Never: return nil, fmt.Errorf("%w: action %d is refused: %s", ErrNotBound, a.Seq, d.Reason) case connectors.Digest(a.Action, a.Input) != a.Digest, d.Action.Digest != a.Digest: return nil, fmt.Errorf("%w: action %d changed after it was judged", ErrNotBound, a.Seq) } out = append(out, runs.ApprovedAction{ Seq: a.Seq, Decision: d, Approval: judgement.Approval{ DecisionID: d.ID, Digest: a.Digest, By: p.AnsweredByID.String, ByID: p.AnsweredByID.String, At: p.AnsweredAt.Time, }, }) } return out, nil }