package runs import ( "context" "fmt" "strings" "github.com/google/uuid" "gopkg.in/yaml.v3" "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/judgement" ) // stateUnrun is what an action an approval covered settles as when an earlier // action of the same approval stopped it. const stateUnrun = "not run" // sequence is one approval that covers a list of steps, with the approval each // step runs under and whether it has stopped. type sequence struct { requestID uuid.UUID steps []coveredStep // stopped is why no later step of the sequence runs, empty while one may. stopped string // counted is whether the approval has already counted for a step that ran, // which leaves it unable to be discarded. counted bool } // coveredStep is one step a sequence covers: the action judged when the person // was asked, and the approval that lets it run. type coveredStep struct { name string decision judgement.Decision approval judgement.Approval } // covered returns the approval that covers the step this name, and its place // in that approval's sequence. func (p *progress) covered(name string) (*sequence, int) { for _, seq := range p.sequences { for i := range seq.steps { if seq.steps[i].name == name { return seq, i } } } return nil, 0 } // step returns the document step with this id. func (p *progress) step(id string) (Step, bool) { for _, s := range p.steps { if s.ID == id { return s, true } } return Step{}, false } // outcomeOf is what became of one covered action. func outcomeOf(d judgement.Decision, state, by, why string) approvalOutcome { return approvalOutcome{ Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID, State: state, By: by, Error: why, digest: d.Action.Digest, } } // approveCovered judges the steps covers names and asks one person to approve // them all, in that order. Each step then runs under that one approval, judged // again first. A step whose action can't be judged now is not covered: an // approval of something other than the action that will run is no approval. func (d Deps) approveCovered(rc *Context, p *progress, name string, covers []string) (StepResult, error) { seq := &sequence{steps: make([]coveredStep, 0, len(covers))} values := scope(p.inputs, p.results) for _, id := range covers { step, ok := p.step(id) if !ok { return StepResult{}, fmt.Errorf("no step has id %q", id) } if missing := unresolved(step.Settings, p.results); len(missing) > 0 { return StepResult{}, fmt.Errorf("%q reads steps %s, which haven't run, so its action can't be judged yet", id, strings.Join(missing, ", ")) } var s actionSettings if err := decodeSettings(renderSettings(step.Settings, values), &s); err != nil { return StepResult{}, fmt.Errorf("%q: %w", id, err) } in, err := actionInput(s) if err != nil { return StepResult{}, fmt.Errorf("%q: %w", id, err) } decision, err := rc.Step("cover:"+id, func(ctx context.Context, key string) (judgement.Decision, error) { return d.Judge.Assess(ctx, rc.request(key, s.Connector, s.Name, in)) }) if err != nil { return StepResult{}, err } if decision.Level == judgement.Never { return StepResult{}, fmt.Errorf("%q is refused: %s", id, decision.Reason) } seq.steps = append(seq.steps, coveredStep{name: id, decision: decision}) } ds := make([]judgement.Decision, len(seq.steps)) for i, cs := range seq.steps { ds[i] = cs.decision } request, answer, err := askThroughPath(rc, d.Approver, d.Settings, name, ds) if err != nil { return StepResult{}, err } seq.requestID = request.ID if request.State != approvals.StateApproved { // A denial or an expiry stops the sequence: no step it covered runs, not // even on a judgement of its own. seq.stopped = "the request was " + request.State if request.State == approvals.StateExpired { seq.stopped = "the request expired" } out := make([]approvalOutcome, 0, len(seq.steps)) for _, cs := range seq.steps { p.settled[cs.decision.Action.Digest] = true out = append(out, outcomeOf(cs.decision, stateUnrun, answer.By, seq.stopped)) } p.outcomes = append(p.outcomes, out...) p.sequences = append(p.sequences, seq) return StepResult{Summary: outcomeLines(out)}, nil } approval := request.Approval(answer) for i := range seq.steps { p.settled[seq.steps[i].decision.Action.Digest] = true seq.steps[i].approval = approval } p.sequences = append(p.sequences, seq) return StepResult{Summary: fmt.Sprintf("%d actions approved by %s", len(seq.steps), answer.By)}, nil } // runCovered runs one step of an approved sequence. The step's action is judged // again first: a judgement that refuses it, is stricter than the one approved, // or names a changed target or effect stops the sequence, as does an action // that fails, and every action after it is reported unrun. func (d Deps) runCovered(rc *Context, p *progress, seq *sequence, i int) (StepResult, error) { cs := seq.steps[i] level := cs.decision.Level.String() if why := seq.stopped; why != "" { res := ranStep(level, outcomeOf(cs.decision, stateUnrun, "", why)) res.Summary = stateUnrun + ": " + why return res, nil } // The steps are named after the decision's key, as one settled alone is, // so the trail folds each reassessment into the action it reassessed. name := cs.decision.Key fresh, err := rc.Step("judge-again:"+name, func(ctx context.Context, key string) (judgement.Decision, error) { return d.Judge.Assess(ctx, rc.request(key, cs.decision.Action.Connector, cs.decision.Action.Name, cs.decision.Action.Input)) }) if err != nil { return StepResult{}, err } out := outcomeOf(cs.decision, approvals.StateApproved, cs.approval.By, "") switch next, why := afterApproval(cs.decision, fresh); next { case runApproval: if _, err := rc.Step("count:"+name, func(ctx context.Context, _ string) (bool, error) { return true, d.Approver.Accept(ctx, seq.requestID) }); err != nil { return StepResult{}, err } seq.counted = true out.State = EffectRan out.Result, out.Error, out.Unknown = runJudged(rc, d.Judge, cs.decision, &cs.approval) case runFresh: // The step no longer needs approval, so it runs on its own judgement // and the approval isn't counted. out.State = EffectRan out.Result, out.Error, out.Unknown = runJudged(rc, d.Judge, fresh, nil) default: // The person approved one act, not whatever the steps become: a step // that no longer matches it isn't asked about again, it stops the rest. out.State, out.Error = approvals.StateDiscarded, why if seq.counted { // An approval that already let an action of the sequence run has // counted and can't be discarded, so the step is reported unrun under // it and the record keeps agreeing with the report. out.State = stateUnrun } else if _, err := rc.Step("discard:"+name, func(ctx context.Context, _ string) (bool, error) { return true, d.Approver.Discard(ctx, seq.requestID, why) }); err != nil { return StepResult{}, err } } p.outcomes = append(p.outcomes, out) p.stopped = p.stopped || out.Unknown if out.State != EffectRan || out.Error != "" || out.Unknown { p.stopSequence(seq, i, firstText(out.Error, "an earlier action of the sequence did not run")) } return ranStep(level, out), nil } // stopSequence reports the actions after the one at from as unrun, so the run // says what the approval covered and did not do. func (p *progress) stopSequence(seq *sequence, from int, why string) { seq.stopped = why for _, cs := range seq.steps[from+1:] { p.outcomes = append(p.outcomes, outcomeOf(cs.decision, stateUnrun, "", why)) } } // unresolved lists the steps a step's settings read that have no result yet. // Their values render empty, so the action they belong to can't be judged now. // The checker refuses an approval that covers such a step, which leaves a // document saved before it did, or a step an earlier condition skipped. func unresolved(settings yaml.Node, results map[string]StepResult) []string { var out []string for _, id := range stepRefs(settings) { if _, done := results[id]; !done { out = append(out, id) } } return out }