Merge branch 'worktree-agent-a82ec64b6cc1a2809'
# Conflicts: # internal/app/archie/operations.go # modules/events/events.go # modules/governance/accounts_api.go # modules/governance/governance.go
This commit is contained in:
44 files changed
+1462
-266
No files matched your search
@@ -0,0 +1,133 @@
|
||||
package runs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
|
||||
// asked is one decision the engine requested.
|
||||
type asked struct {
|
||||
principal governance.IdentityID
|
||||
action governance.Action
|
||||
kind governance.ResourceKind
|
||||
id string
|
||||
}
|
||||
|
||||
// recordingAccess answers every Authorize with one fixed decision and records
|
||||
// what was asked.
|
||||
type recordingAccess struct {
|
||||
decision governance.Decision
|
||||
calls []asked
|
||||
}
|
||||
|
||||
func (r *recordingAccess) Authorize(_ context.Context, p governance.Principal, a governance.Action, res governance.Resource, _ governance.AccessContext) governance.Decision {
|
||||
r.calls = append(r.calls, asked{p.IdentityID, a, res.Kind, res.ID})
|
||||
return r.decision
|
||||
}
|
||||
|
||||
// queueingStore holds the runs the engine queues.
|
||||
type queueingStore struct {
|
||||
fakeWork
|
||||
queued []store.NewRun
|
||||
}
|
||||
|
||||
func (q *queueingStore) Start(_ context.Context, n store.NewRun) (uuid.UUID, error) {
|
||||
q.queued = append(q.queued, n)
|
||||
return uuid.New(), nil
|
||||
}
|
||||
|
||||
// claimsOne hands out one queued run to the worker, as the store does after a
|
||||
// restart or a retry.
|
||||
type claimsOne struct {
|
||||
*queueingStore
|
||||
run store.Run
|
||||
}
|
||||
|
||||
func (c claimsOne) Claim(context.Context, string, uuid.UUID, time.Duration) (store.Run, bool, error) {
|
||||
return c.run, true, nil
|
||||
}
|
||||
|
||||
// TestRunsAreAuthorizedAtStartAndAtEveryClaim guards that a run started by a
|
||||
// trigger and the same run claimed again after a restart or a retry are decided
|
||||
// by the same live check, as the workload principal, and that a refusal stops
|
||||
// the work. A policy chain that can't decide starts nothing, finishes nothing
|
||||
// and leaves the run for another attempt. Without it a revoked grant would
|
||||
// keep running queued work.
|
||||
func TestRunsAreAuthorizedAtStartAndAtEveryClaim(t *testing.T) {
|
||||
workload := asked{governance.WorkloadID, governance.ActionRun, governance.KindWorkflow, "triage"}
|
||||
tests := []struct {
|
||||
name string
|
||||
decision governance.Decision
|
||||
noPrincipal bool
|
||||
claim bool
|
||||
wantCalls []asked
|
||||
wantQueued int
|
||||
wantRan bool
|
||||
wantFinished []string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "a trigger starts its run", decision: governance.Allowed(), wantCalls: []asked{workload}, wantQueued: 1},
|
||||
{name: "a start with no principal", decision: governance.Allowed(), noPrincipal: true, wantErr: governance.ErrDenied},
|
||||
{name: "a revoked start", decision: governance.DeniedAt(governance.LevelOrg, []string{"org-workload"}), wantCalls: []asked{workload}, wantErr: governance.ErrDenied},
|
||||
{name: "a start the chain can't decide", decision: governance.Unavailable(), wantCalls: []asked{workload}, wantErr: governance.ErrChainUnavailable},
|
||||
{name: "a claim after a restart", decision: governance.Allowed(), claim: true, wantCalls: []asked{workload}, wantRan: true, wantFinished: []string{store.StateSucceeded}},
|
||||
{name: "a claim after revocation", decision: governance.DeniedAt(governance.LevelOrg, []string{"org-workload"}), claim: true, wantCalls: []asked{workload}, wantFinished: []string{store.StateFailed}},
|
||||
{name: "a claim the chain can't decide", decision: governance.Unavailable(), claim: true, wantCalls: []asked{workload}, wantErr: governance.ErrChainUnavailable},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
work := &queueingStore{}
|
||||
access := &recordingAccess{decision: tt.decision}
|
||||
engine := newEngine(nil, work, slog.New(slog.DiscardHandler), Options{})
|
||||
engine.queue = work
|
||||
engine.Use(Deps{Access: access})
|
||||
ran := false
|
||||
useWorkflow(engine, func(*Context, jsontext.Value) (jsontext.Value, error) {
|
||||
ran = true
|
||||
return jsontext.Value(`"done"`), nil
|
||||
})
|
||||
|
||||
var err error
|
||||
if tt.claim {
|
||||
engine.work = claimsOne{work, store.Run{ID: uuid.New(), OrgID: "org", Workflow: "triage", Version: 1, Input: jsontext.Value(`null`)}}
|
||||
_, err = engine.claimAndExecute(t.Context())
|
||||
} else {
|
||||
ctx := t.Context()
|
||||
if !tt.noPrincipal {
|
||||
ctx = governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID))
|
||||
}
|
||||
_, err = engine.Start(ctx, StartRequest{OrgID: "org", Workflow: "triage", Key: "event:trigger"})
|
||||
}
|
||||
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
if !slices.Equal(access.calls, tt.wantCalls) {
|
||||
t.Fatalf("decisions asked = %v, want %v", access.calls, tt.wantCalls)
|
||||
}
|
||||
if len(work.queued) != tt.wantQueued {
|
||||
t.Fatalf("runs queued = %d, want %d", len(work.queued), tt.wantQueued)
|
||||
}
|
||||
if ran != tt.wantRan {
|
||||
t.Fatalf("workflow ran = %v, want %v", ran, tt.wantRan)
|
||||
}
|
||||
if !slices.Equal(work.finished, tt.wantFinished) {
|
||||
t.Fatalf("finished = %v, want %v", work.finished, tt.wantFinished)
|
||||
}
|
||||
if slices.Contains(tt.wantFinished, store.StateFailed) && !strings.Contains(work.errors[0], "not permitted") {
|
||||
t.Fatalf("the run's trail says %q, want the refusal", work.errors[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -73,6 +73,9 @@ type DryRequest struct {
|
||||
// StartDry queues a dry run of a document and returns its run's id. A document
|
||||
// that doesn't validate starts nothing.
|
||||
func (e *Engine) StartDry(ctx context.Context, req DryRequest) (uuid.UUID, error) {
|
||||
if err := e.mayStart(ctx, req.Workflow); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
doc, err := e.validateDocument(ctx, req.Document)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
@@ -93,7 +96,7 @@ func (e *Engine) StartDry(ctx context.Context, req DryRequest) (uuid.UUID, error
|
||||
if err := doc.checkInputs(decodeInputs(input)); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("workflow %q: %w", req.Workflow, err)
|
||||
}
|
||||
return e.db.Start(ctx, store.NewRun{
|
||||
return e.queue.Start(ctx, store.NewRun{
|
||||
OrgID: req.OrgID, Workflow: req.Workflow, Input: input, Dry: true, Overlay: overlay,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
@@ -48,6 +49,7 @@ func (anyBox) Tool(string) (connectors.Tool, bool) { return nil, true }
|
||||
// is queued.
|
||||
func TestStartDryRefusesWhatCannotStart(t *testing.T) {
|
||||
engine := newEngine(nil, &fakeWork{}, slog.New(slog.DiscardHandler), Options{})
|
||||
engine.Use(Deps{Access: &recordingAccess{decision: governance.Allowed()}})
|
||||
tests := []struct {
|
||||
name string
|
||||
doc string
|
||||
@@ -71,7 +73,8 @@ func TestStartDryRefusesWhatCannotStart(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, err := engine.StartDry(context.Background(), DryRequest{
|
||||
ctx := governance.WithPrincipal(context.Background(), governance.SharedTokenOwner())
|
||||
_, err := engine.StartDry(ctx, DryRequest{
|
||||
OrgID: "org", Workflow: "draft", Document: tt.doc,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
|
||||
@@ -103,6 +103,10 @@ type Deps struct {
|
||||
// Capabilities is what saving a workflow checks connector references
|
||||
// against.
|
||||
Capabilities Capabilities
|
||||
// Access decides whether a run may start and whether a claimed run may
|
||||
// execute, for the principal acting or else the workload principal. With
|
||||
// none, no run starts or executes.
|
||||
Access governance.Authorizer
|
||||
}
|
||||
|
||||
// Workflow is a document ready to run: the code that executes its steps for
|
||||
|
||||
+71
-10
@@ -64,12 +64,14 @@ type runStarter interface {
|
||||
|
||||
// Engine starts, executes and resumes runs.
|
||||
type Engine struct {
|
||||
db *store.Store
|
||||
work runWork
|
||||
log *slog.Logger
|
||||
opts Options
|
||||
mu sync.RWMutex
|
||||
deps *Deps
|
||||
db *store.Store
|
||||
// queue starts runs; it is db except in tests.
|
||||
queue runQueue
|
||||
work runWork
|
||||
log *slog.Logger
|
||||
opts Options
|
||||
mu sync.RWMutex
|
||||
deps *Deps
|
||||
// load turns a claimed run into the code that executes it.
|
||||
load func(ctx context.Context, run store.Run) (Workflow, error)
|
||||
}
|
||||
@@ -93,7 +95,7 @@ func newEngine(db *store.Store, work runWork, log *slog.Logger, opts Options) *E
|
||||
if opts.Owner == "" {
|
||||
opts.Owner = "archie"
|
||||
}
|
||||
e := &Engine{db: db, work: work, log: log, opts: opts}
|
||||
e := &Engine{db: db, queue: db, work: work, log: log, opts: opts}
|
||||
e.load = e.loadDocument
|
||||
return e
|
||||
}
|
||||
@@ -185,14 +187,42 @@ func (e *Engine) Has(ctx context.Context, orgID, name string) (bool, error) {
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// runQueue reads the workflow a run starts under and queues the run.
|
||||
type runQueue interface {
|
||||
workflowFinder
|
||||
Start(ctx context.Context, n store.NewRun) (uuid.UUID, error)
|
||||
}
|
||||
|
||||
// Start queues a run under the latest stored version of its workflow and
|
||||
// returns its id.
|
||||
// returns its id. The principal in ctx must be allowed to run the workflow;
|
||||
// work that starts runs on its own, such as a trigger, passes the workload
|
||||
// principal. A start the policy chain can't decide queues nothing, and the
|
||||
// error wraps governance.ErrChainUnavailable so the caller tries again.
|
||||
func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error) {
|
||||
n, err := newRun(ctx, e.db, req)
|
||||
if err := e.mayStart(ctx, req.Workflow); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
n, err := newRun(ctx, e.queue, req)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return e.db.Start(ctx, n)
|
||||
return e.queue.Start(ctx, n)
|
||||
}
|
||||
|
||||
// mayStart refuses a start by a caller who may not run workflow, or whose
|
||||
// right can't be checked.
|
||||
func (e *Engine) mayStart(ctx context.Context, workflow string) error {
|
||||
p, ok := governance.PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: no principal starts the run", governance.ErrDenied)
|
||||
}
|
||||
deps, err := e.steps()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
|
||||
}
|
||||
return governance.Require(ctx, deps.Access, p, governance.ActionRun, governance.Resource{
|
||||
Kind: governance.KindWorkflow, ID: workflow, Org: p.Org,
|
||||
})
|
||||
}
|
||||
|
||||
// workflowFinder reads stored workflow versions.
|
||||
@@ -320,10 +350,41 @@ func (e *Engine) claimAndExecute(ctx context.Context) (bool, error) {
|
||||
if err != nil || !ok {
|
||||
return false, err
|
||||
}
|
||||
if err := e.mayExecute(ctx, run); err != nil {
|
||||
return e.refuseClaim(ctx, run, token, err)
|
||||
}
|
||||
e.execute(ctx, run, token)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// mayExecute rechecks, each time a worker claims a run, that the workload
|
||||
// principal may still run its workflow. A new run, a retry and a resume after
|
||||
// a crash or a wake-up all pass through here.
|
||||
func (e *Engine) mayExecute(ctx context.Context, run store.Run) error {
|
||||
deps, err := e.steps()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
|
||||
}
|
||||
return governance.RequireWorkload(ctx, deps.Access, governance.ActionRun, governance.Resource{
|
||||
Kind: governance.KindWorkflow, ID: run.Workflow,
|
||||
})
|
||||
}
|
||||
|
||||
// refuseClaim handles a claimed run that may not execute. A policy chain that
|
||||
// can't decide leaves the run unfinished, so its lease lapses and a worker
|
||||
// claims it again. A refusal ends the run as failed, and its trail says why.
|
||||
func (e *Engine) refuseClaim(ctx context.Context, run store.Run, token uuid.UUID, cause error) (bool, error) {
|
||||
if !errors.Is(cause, governance.ErrDenied) {
|
||||
return false, fmt.Errorf("run %s waits for access policies: %w", run.ID, cause)
|
||||
}
|
||||
ended := store.Ended{State: store.StateFailed, Error: cause.Error()}
|
||||
if err := e.work.Finish(ctx, run.ID, token, ended); err != nil {
|
||||
return false, fmt.Errorf("finish refused run %s: %w", run.ID, err)
|
||||
}
|
||||
e.log.WarnContext(ctx, "run refused", "run", run.ID, "workflow", run.Workflow, "error", cause)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// execute runs one claimed run to its next suspension or end. The run's
|
||||
// context ends if the lease can't be renewed, so a stale worker stops.
|
||||
func (e *Engine) execute(ctx context.Context, run store.Run, token uuid.UUID) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
@@ -139,19 +140,19 @@ type Approvals interface {
|
||||
func (e *Engine) Register(api huma.API, orgID string, origins Origins, decisions Decisions, asked Approvals) {
|
||||
a := &runAPI{engine: e, db: e.db, orgID: orgID, origins: origins, decisions: decisions, approvals: asked}
|
||||
tags := []string{"Runs"}
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindRun), huma.Operation{
|
||||
OperationID: "list-runs", Method: http.MethodGet, Path: "/api/runs",
|
||||
Summary: "List recent runs", Tags: tags,
|
||||
}, a.recent)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindRun), huma.Operation{
|
||||
OperationID: "get-run", Method: http.MethodGet, Path: "/api/runs/{id}",
|
||||
Summary: "Get a run's decision trail", Tags: tags,
|
||||
}, a.trail)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindRun), huma.Operation{
|
||||
OperationID: "retry-run", Method: http.MethodPost, Path: "/api/runs/{id}/retry",
|
||||
Summary: "Retry a parked run from a step, keeping the results of the steps before it", Tags: tags,
|
||||
}, a.retry)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindRun), huma.Operation{
|
||||
OperationID: "cancel-run", Method: http.MethodPost, Path: "/api/runs/{id}/cancel",
|
||||
Summary: "Cancel a run and the runs it started with workflow.call", Tags: tags,
|
||||
}, a.cancel)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/stableid"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs/internal/store"
|
||||
)
|
||||
|
||||
@@ -43,19 +44,19 @@ type workflowAPI struct {
|
||||
func (e *Engine) registerWorkflows(api huma.API, orgID string) {
|
||||
a := &workflowAPI{e: e, orgID: orgID}
|
||||
tags := []string{"Workflows"}
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "list-workflows", Method: http.MethodGet, Path: "/api/workflows",
|
||||
Summary: "List every workflow at its latest version", Tags: tags,
|
||||
}, a.list)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "get-workflow", Method: http.MethodGet, Path: "/api/workflows/{name}",
|
||||
Summary: "Get a workflow", Tags: tags,
|
||||
}, a.get)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "put-workflow", Method: http.MethodPut, Path: "/api/workflows/{name}",
|
||||
Summary: "Save a workflow document as its next version", Tags: tags,
|
||||
}, a.put)
|
||||
huma.Register(api, huma.Operation{
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindWorkflow), huma.Operation{
|
||||
OperationID: "list-workflow-step-types", Method: http.MethodGet, Path: "/api/workflow-step-types",
|
||||
Summary: "List the step types a workflow document may name, with their settings schemas", Tags: tags,
|
||||
}, a.stepTypes)
|
||||
|
||||
Reference in new issue
Block a user