feat(eda): wire action playbooks through loader and module schemas
Pass 2 of archie-core-nx30. Pass 1 typed each prior action's result in
the CEL env; this pass wires that typing through the loader, module
schemas, and daemon, and removes the now-redundant id classifier.
Loader shape (D2): one playbook is exactly one workflow action
(unchanged) OR one or more module actions; the shapes never mix. Mixed,
unsupported, or zero actions fail the load naming the playbook.
playbook.Load now takes a KindSchemas source (a small interface this
package defines, satisfied by *module.ModuleRegistry) so playbook grows
no module import. Callers: bootstrap.loadEDAPlaybooks passes b.modules;
daemon and playbook tests pass module.New().
Per-playbook env (D3): each action's when and args values compile against
an env built from the PRIOR actions' ids typed by their kinds' Result
structs (expr.NewEnv(DeclaredResult{ID,Type})). event stays dyn. An
undeclared id, a forward reference, or a field the kind's Result lacks is
a compile-time undefined-field error.
Args schema (D4): an args key the kind's Args struct does not define
fails the load. An args VALUE whose compiled type mismatches the field
type is left as a named gap (not cheap without leaking cel-go type kinds
into playbook and handling dyn reads); a wrong-typed value still surfaces
at module invoke, not load.
D1: Store.Dispatch routes workflow playbooks only, so an action playbook
cannot hijack the definition pin. bootstrap.loadEDAPlaybooks logs a
visible Warn (not debug) for each loaded action playbook naming it and
stating it does not execute yet.
D5: ModuleRegistry.Invoke is deliberately schema-agnostic (the stored
invoker is type-erased and returns map[string]any). The map-to-Result
marshalling belongs in the coordinator named by the doc, which is the
t2db.31 run path and out of scope here.
Classifier enumeration (E) and verdict, all proven for a typed action
playbook via CEL (expr.NewEnv with a declared log.Result id):
unknown id CEL compile (undefined field) -> delete unknownActionReference
literal map index actions["x"] CEL compile (no _[_] overload) -> covered
computed index actions[key] CEL compile (undeclared 'key') -> covered
dynamic index actions[event.name] CEL compile (no _[_] overload) -> covered
"x" in actions CEL compile (no @in overload) -> covered
size(actions) CEL compile (no size overload) -> covered
actions.all(...) CEL compile (not a range) -> covered
actions == {} CEL compile (no _==_ overload) -> covered
bare actions compiles; KEPT classifier -> retained resolvable check
unknownActionReference is deleted; actionReferences/ActionReferences are
kept solely for the bare-actions spelling CEL does not reject.
This commit is contained in:
1 parent
c53a4ab6bf
commit
eaf29459d7
9 files changed
+664
-198
No files matched your search
@@ -764,20 +764,26 @@ func (b *boot) loadModules(cfg config.Config, log *slog.Logger) error {
|
||||
}
|
||||
|
||||
// loadEDAPlaybooks loads the EDA playbook documents (t2db.15): trigger +
|
||||
// single workflow-kind action with CEL when conditions and args values.
|
||||
// Loaded at startup with the same reject-at-load rule -- any malformed
|
||||
// playbook, multi-action playbook, non-workflow position, when compile
|
||||
// failure, or args compile failure aborts startup, matching the routing-file
|
||||
// load pattern (not degrade-and-skip). A nonexistent dir is an empty store.
|
||||
// Split out of loadWorkflows (t2db.16); pure extraction, same log messages as
|
||||
// before.
|
||||
// workflow-kind actions and module-kind action playbooks with CEL when
|
||||
// conditions and args values. Loaded at startup with the same reject-at-load
|
||||
// rule -- any malformed playbook, mixed/unsupported action shape, unknown
|
||||
// module kind, when compile failure, or args key failure aborts startup,
|
||||
// matching the routing-file load pattern (not degrade-and-skip). A nonexistent
|
||||
// dir is an empty store. Action playbooks load and type-check but have no run
|
||||
// path yet (t2db.31), so each one is logged as a visible warning here rather
|
||||
// than routed by the definition pin.
|
||||
func (b *boot) loadEDAPlaybooks(cfg config.Config, log *slog.Logger) error {
|
||||
var err error
|
||||
b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir)
|
||||
b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir, b.modules)
|
||||
if err != nil {
|
||||
log.Error("eda playbook load failed", "dir", cfg.EDAPlaybookDir, "err", err)
|
||||
return err
|
||||
}
|
||||
for _, pb := range b.playbooks.Playbooks {
|
||||
if len(pb.Actions) != 1 || pb.Actions[0].Position != "workflow" {
|
||||
log.Warn("eda action playbook loaded: action playbooks do not execute yet", "playbook", pb.ID)
|
||||
}
|
||||
}
|
||||
log.Info("eda playbooks loaded", "dir", cfg.EDAPlaybookDir, "playbooks", len(b.playbooks.Playbooks))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
)
|
||||
|
||||
// TestLoadEDAPlaybooksWarnsOnActionPlaybook pins the D1 visible warning: an
|
||||
// action playbook loads and validates but has no run path yet, so the daemon
|
||||
// logs a warning (not debug) naming it and stating plainly that action
|
||||
// playbooks do not execute yet -- rather than silently loading a playbook that
|
||||
// can never be routed.
|
||||
func TestLoadEDAPlaybooksWarnsOnActionPlaybook(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(`trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"build started"'
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
log := slog.New(slog.NewTextHandler(&buf, nil))
|
||||
b := &boot{cfg: config.Config{EDAPlaybookDir: dir}, modules: module.New()}
|
||||
if err := b.loadEDAPlaybooks(b.cfg, log); err != nil {
|
||||
t.Fatalf("loadEDAPlaybooks: %v", err)
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "pb.yaml") {
|
||||
t.Errorf("warning output does not name the action playbook: %q", out)
|
||||
}
|
||||
if !strings.Contains(out, "do not execute yet") {
|
||||
t.Errorf("warning output does not state action playbooks do not execute yet: %q", out)
|
||||
}
|
||||
if strings.Contains(out, "level=DEBUG") {
|
||||
t.Errorf("warning output was logged at debug, want a visible warning: %q", out)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
@@ -20,7 +21,7 @@ func playbookStore(t *testing.T, document string) *playbook.Store {
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(document), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := playbook.Load(dir)
|
||||
loaded, err := playbook.Load(dir, module.New())
|
||||
if err != nil {
|
||||
t.Fatalf("load playbook: %v", err)
|
||||
}
|
||||
|
||||
@@ -259,22 +259,24 @@ func (e *Env) Compile(src string) (*Program, error) {
|
||||
// the `actions` context root as either a statically-resolvable action id or
|
||||
// not. The invariant is exhaustive by construction: each read of `actions`
|
||||
// consumes exactly one `actions` identifier node, so counting identifier
|
||||
// nodes and counting the reads that match one of the two static access
|
||||
// shapes (a field selection on the `actions` ident, or a map index whose key
|
||||
// is a string literal) yields
|
||||
// nodes and counting the reads that match the static access shape (a field
|
||||
// selection on the `actions` ident) yields
|
||||
//
|
||||
// resolvable = (identCount == staticCount)
|
||||
//
|
||||
// Any other spelling that mentions `actions` contributes an identifier node
|
||||
// without a matching static access, so it reports unresolvable rather than
|
||||
// slipping through as a runtime miss. The returned ids are the sorted,
|
||||
// de-duplicated ids of the static accesses, for the playbook loader's
|
||||
// unknown-id check.
|
||||
// de-duplicated ids of the static accesses.
|
||||
//
|
||||
// With the per-playbook object type the checker already rejects every
|
||||
// non-static `actions` read at compile time, so a program that reaches this
|
||||
// walk is resolvable by construction; the walk is retained until the next
|
||||
// pass removes it together with the loader's duplicate unknown-id check.
|
||||
// With the per-playbook object type the CEL checker rejects every non-static
|
||||
// `actions` read at compile time -- a dynamic index, `in`, `size`, or a
|
||||
// method/field selection that is not a declared id never reaches this walk.
|
||||
// The one spelling the checker does NOT reject is a bare `actions` value
|
||||
// read, which compiles as an object value but cannot be pinned to an action
|
||||
// id at load. This walk is retained solely to reject that spelling; the ids
|
||||
// return is now informational (the unknown-id check moved to the checker's
|
||||
// per-playbook object type).
|
||||
func actionReferences(ast *cel.Ast) ([]string, bool) {
|
||||
if ast == nil || ast.NativeRep() == nil {
|
||||
return nil, true
|
||||
@@ -294,24 +296,6 @@ func actionReferences(ast *cel.Ast) ([]string, bool) {
|
||||
}
|
||||
staticCount++
|
||||
seen[sel.FieldName()] = struct{}{}
|
||||
case celast.CallKind:
|
||||
call := e.AsCall()
|
||||
if call.FunctionName() != "_[_]" || len(call.Args()) != 2 {
|
||||
return
|
||||
}
|
||||
if !isActionsIdent(call.Args()[0]) {
|
||||
return
|
||||
}
|
||||
key := call.Args()[1]
|
||||
if key.Kind() != celast.LiteralKind {
|
||||
return
|
||||
}
|
||||
id, ok := key.AsLiteral().Value().(string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
staticCount++
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
})
|
||||
celast.PreOrderVisit(ast.NativeRep().Expr(), visitor)
|
||||
@@ -340,8 +324,10 @@ type Program struct {
|
||||
// read could be statically resolved to one of those ids. ids is empty when
|
||||
// the expression reads no prior-action result; resolvable is false when the
|
||||
// expression reads `actions` in any form that cannot be pinned to a prior
|
||||
// action id at load. The playbook loader rejects a non-resolvable program
|
||||
// rather than evaluating it as a runtime miss.
|
||||
// action id at load. Under the per-playbook object type the checker already
|
||||
// rejects every dynamic `actions` read, so the only form that still reaches
|
||||
// here unresolved is a bare `actions` value read; the playbook loader rejects
|
||||
// that rather than evaluating it as a runtime miss.
|
||||
func (p *Program) ActionReferences() (ids []string, resolvable bool) {
|
||||
if p == nil {
|
||||
return nil, true
|
||||
|
||||
@@ -36,6 +36,12 @@ type Kind struct {
|
||||
// exportPath is the fixed exported function name the interpreted file
|
||||
// must define (e.g. "main.Run").
|
||||
exportPath string
|
||||
// argsType and resultType are the kind's hand-written Args and Result
|
||||
// struct types. They are the schema the playbook loader declares to CEL
|
||||
// so an arg key or result field typo is a load failure rather than a
|
||||
// dispatch failure (multi-action-playbooks.md, D4).
|
||||
argsType reflect.Type
|
||||
resultType reflect.Type
|
||||
}
|
||||
|
||||
// registry maps kind name to its one typed contract. Adding a new kind is a
|
||||
@@ -44,6 +50,8 @@ var registry = map[string]Kind{
|
||||
"log": {
|
||||
loadSymbols: func() map[string]map[string]reflect.Value { return logextract.Symbols },
|
||||
exportPath: "main.Run",
|
||||
argsType: reflect.TypeFor[log.Args](),
|
||||
resultType: reflect.TypeFor[log.Result](),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -82,6 +90,20 @@ func (r *ModuleRegistry) Len() int {
|
||||
return len(r.kinds)
|
||||
}
|
||||
|
||||
// KindSchema reports the hand-written Args and Result struct types for a
|
||||
// known kind. A kind is known when it has a registered contract in this
|
||||
// package's built-in registry (the log kind is the shipped kind), independent
|
||||
// of whether a module instance is currently loaded from a module directory.
|
||||
// It is the narrow schema source the playbook loader consumes to type-check
|
||||
// an action playbook's args and result references at load.
|
||||
func (r *ModuleRegistry) KindSchema(kind string) (reflect.Type, reflect.Type, bool) {
|
||||
k, ok := registry[kind]
|
||||
if !ok {
|
||||
return nil, nil, false
|
||||
}
|
||||
return k.argsType, k.resultType, true
|
||||
}
|
||||
|
||||
// Register discovers <dir>/<kind>.go, interprets it against the kind's
|
||||
// generated symbols, resolves its fixed export, and stores the invoker.
|
||||
// A missing file, an unreadable file, a resolve failure, or an unknown kind
|
||||
|
||||
@@ -4,8 +4,11 @@ import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module/log"
|
||||
)
|
||||
|
||||
func writeModule(t *testing.T, dir, content string) string {
|
||||
@@ -58,6 +61,23 @@ func TestRegisterUnknownKindIsError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindSchema(t *testing.T) {
|
||||
r := New()
|
||||
argsType, resultType, ok := r.KindSchema("log")
|
||||
if !ok {
|
||||
t.Fatal("KindSchema(log) = not ok, want the built-in log contract")
|
||||
}
|
||||
if argsType != reflect.TypeFor[log.Args]() {
|
||||
t.Errorf("KindSchema(log) args = %v, want log.Args", argsType)
|
||||
}
|
||||
if resultType != reflect.TypeFor[log.Result]() {
|
||||
t.Errorf("KindSchema(log) result = %v, want log.Result", resultType)
|
||||
}
|
||||
if _, _, ok := r.KindSchema("notify"); ok {
|
||||
t.Fatal("KindSchema(notify) = ok, want false for an unregistered kind")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterMissingFileIsError(t *testing.T) {
|
||||
r := New()
|
||||
if err := r.Register("log", t.TempDir()); err == nil {
|
||||
|
||||
@@ -142,7 +142,7 @@ actions:
|
||||
workflow: tdd
|
||||
id: notify
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
// Package playbook is the EDA playbook document type and its event
|
||||
// coordinator: the rich trigger+actions YAML shape (docs/prds/
|
||||
// eda-playbook-engine.md) with CEL `when` conditions and `args` values
|
||||
// (open question 1, resolved to CEL). This slice is deliberately single-action,
|
||||
// workflow-position only: multi-action playbooks and Module/Channel/Forge
|
||||
// action positions remain blocked on the unresolved execution-time gaps
|
||||
// (mid-run failure semantics, idempotency for non-workflow actions) and are
|
||||
// rejected at load -- the hard boundary, not to be relaxed without sign-off.
|
||||
// (open question 1, resolved to CEL). A playbook is one of two shapes
|
||||
// (multi-action-playbooks.md, D2):
|
||||
//
|
||||
// This is an ADDITIONAL routing source alongside the flat kind/label binding
|
||||
// files (t2db.9/.10/.11): the daemon consults a matching playbook before
|
||||
// those bindings when it pins a task's workflow definition (t2db.23). The
|
||||
// binding loaders themselves are untouched.
|
||||
// - a workflow playbook is exactly one `workflow` action, unchanged from
|
||||
// the original boundary, and is routed by the daemon's definition pin;
|
||||
// - an action playbook is one or more `module` actions in order, each with
|
||||
// a registered `kind`, `args`, and an optional `when`/`id`. It loads and
|
||||
// type-checks now but has no run path yet (t2db.31).
|
||||
//
|
||||
// The two shapes never mix in one playbook. This is an ADDITIONAL routing
|
||||
// source alongside the flat kind/label binding files (t2db.9/.10/.11): the
|
||||
// daemon consults a matching workflow playbook before those bindings when it
|
||||
// pins a task's workflow definition (t2db.23). The binding loaders themselves
|
||||
// are untouched.
|
||||
package playbook
|
||||
|
||||
import (
|
||||
@@ -18,6 +22,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -28,10 +33,19 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
)
|
||||
|
||||
// KindSchemas is the narrow kind-to-schema source the loader consults to
|
||||
// type-check an action playbook: each module kind's hand-written Args and
|
||||
// Result struct types. *module.ModuleRegistry satisfies it, so the playbook
|
||||
// package grows no import of the module package.
|
||||
type KindSchemas interface {
|
||||
// KindSchema reports the Args and Result reflect types for a known kind;
|
||||
// ok is false when kind is not a registered module kind.
|
||||
KindSchema(kind string) (args, result reflect.Type, ok bool)
|
||||
}
|
||||
|
||||
// Store is the loaded set of playbooks, validated and compiled at load time.
|
||||
type Store struct {
|
||||
Playbooks []*Playbook
|
||||
exprEnv *expr.Env
|
||||
}
|
||||
|
||||
// Playbook is one trigger+actions document.
|
||||
@@ -65,8 +79,9 @@ type Trigger struct {
|
||||
Labels []string
|
||||
}
|
||||
|
||||
// Action is one step in a playbook. Exactly one action per playbook in this
|
||||
// slice, position MUST be "workflow".
|
||||
// Action is one step in a playbook. A workflow action names a workflow
|
||||
// definition; a module action names a registered module kind and is not
|
||||
// routed yet.
|
||||
type Action struct {
|
||||
Position string
|
||||
// ID is an optional stable identifier for this action. When present it
|
||||
@@ -74,6 +89,9 @@ type Action struct {
|
||||
// (actions.<id>); the shape is the shared stable-identifier grammar
|
||||
// (internal/plugin/host.go, internal/domain/workflow/vocabulary.go).
|
||||
ID string
|
||||
// Kind is the module kind name (position: module only); empty for a
|
||||
// workflow action.
|
||||
Kind string
|
||||
// Workflow is the name of the workflow definition to dispatch to
|
||||
// (position: workflow only).
|
||||
Workflow string
|
||||
@@ -82,6 +100,13 @@ type Action struct {
|
||||
// Args holds the action's compiled CEL args values, keyed by arg name.
|
||||
// Nil or empty means the action takes no args.
|
||||
Args map[string]*expr.Program
|
||||
|
||||
// env is the per-action CEL environment this action's expressions were
|
||||
// compiled against: the prior actions' declared ids and their kinds'
|
||||
// Result types. It is also the eval receiver for When/Args. It is unset
|
||||
// only for a hand-built Action (tests, pre-load composition); loaded
|
||||
// actions always carry it.
|
||||
env *expr.Env
|
||||
}
|
||||
|
||||
// rawPlaybook is the YAML document shape before compilation.
|
||||
@@ -113,9 +138,9 @@ var actionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
|
||||
|
||||
// validateActionIDs enforces the id shape and uniqueness across a playbook's
|
||||
// raw actions. An absent id is fine (ids are optional); a declared id must
|
||||
// match the stable-identifier grammar and may not repeat. Uniqueness is
|
||||
// unreachable through Load while the one-action boundary holds, so this helper
|
||||
// is unit-tested directly for the duplicate case.
|
||||
// match the stable-identifier grammar and may not repeat. With action
|
||||
// playbooks now loadable, duplicate ids are reachable through Load, so this
|
||||
// helper is the load-boundary's id gate for both shapes.
|
||||
func validateActionIDs(actions []rawAction) error {
|
||||
seen := make(map[string]struct{}, len(actions))
|
||||
for _, a := range actions {
|
||||
@@ -134,37 +159,18 @@ func validateActionIDs(actions []rawAction) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// unknownActionReference returns the first statically-resolved action id a
|
||||
// compiled `when` reads that is not declared on any action before index idx.
|
||||
// The comparison is against earlier actions' declared ids (the general rule
|
||||
// from J1), so it stays correct when the one-action boundary later relaxes;
|
||||
// today idx is always 0, so any actions.<id> reference is unknown.
|
||||
func unknownActionReference(raw []rawAction, idx int, ids []string) (string, bool) {
|
||||
declared := make(map[string]struct{}, idx)
|
||||
for _, prior := range raw[:idx] {
|
||||
if prior.ID != "" {
|
||||
declared[prior.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, id := range ids {
|
||||
if _, ok := declared[id]; !ok {
|
||||
return id, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Load reads every *.yaml/*.yml playbook in dir, validates each against the
|
||||
// hard boundary (exactly one action, position workflow), and compiles each
|
||||
// when expression and args value. ANY failure -- malformed YAML, a
|
||||
// multi-action playbook, a non-workflow position, a when compile error, an
|
||||
// args compile error -- fails the whole load: the reject-at-load philosophy
|
||||
// of the parent design doc. A missing directory is an empty store (matching
|
||||
// the flat binding loaders' convention).
|
||||
func Load(dir string) (*Store, error) {
|
||||
// two-shape boundary (exactly one workflow action, or one or more module
|
||||
// actions; never mixed), and compiles each when expression and args value
|
||||
// against the action's per-playbook environment. ANY failure -- malformed
|
||||
// YAML, a mixed/unsupported/empty action shape, an unknown kind, a when
|
||||
// compile error, an args key error -- fails the whole load: the reject-at-load
|
||||
// philosophy of the parent design doc. A missing directory is an empty store
|
||||
// (matching the flat binding loaders' convention).
|
||||
func Load(dir string, schemas KindSchemas) (*Store, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
return &Store{exprEnv: expr.NewEnv()}, nil
|
||||
return &Store{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read playbook dir %s: %w", dir, err)
|
||||
@@ -181,10 +187,10 @@ func Load(dir string) (*Store, error) {
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
store := &Store{exprEnv: expr.NewEnv()}
|
||||
store := &Store{}
|
||||
for _, name := range names {
|
||||
path := filepath.Join(dir, name)
|
||||
pb, err := loadOne(dir, path, store.exprEnv)
|
||||
pb, err := loadOne(dir, path, schemas)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -195,7 +201,7 @@ func Load(dir string) (*Store, error) {
|
||||
|
||||
// loadOne loads and validates a single playbook file, deriving its stable ID
|
||||
// (path relative to the configured root) and a content-hash Version.
|
||||
func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
|
||||
func loadOne(dir, path string, schemas KindSchemas) (*Playbook, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read playbook %s: %w", path, err)
|
||||
@@ -226,73 +232,157 @@ func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
|
||||
if err := pb.Trigger.Kind.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("playbook %s: %w", path, err)
|
||||
}
|
||||
|
||||
// HARD BOUNDARY (t2db.15): exactly one action, position workflow only.
|
||||
if len(raw.Actions) != 1 {
|
||||
return nil, fmt.Errorf(
|
||||
"playbook %s: exactly one action is supported; got %d (multi-action playbooks are blocked on unresolved execution-time gaps)",
|
||||
path, len(raw.Actions),
|
||||
)
|
||||
}
|
||||
a := raw.Actions[0]
|
||||
b := "workflow"
|
||||
if a.Position == "" {
|
||||
// Default position for a single bare workflow name stays workflow for
|
||||
// the smallest-useful case.
|
||||
a.Position = b
|
||||
}
|
||||
if a.Position != b {
|
||||
return nil, fmt.Errorf(
|
||||
"playbook %s: action position %q is not supported; only %q actions ship (Module/Channel/Forge positions are blocked on unresolved execution-time gaps)",
|
||||
path, a.Position, b,
|
||||
)
|
||||
}
|
||||
if strings.TrimSpace(a.Workflow) == "" {
|
||||
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", path)
|
||||
}
|
||||
if err := validateActionIDs(raw.Actions); err != nil {
|
||||
return nil, fmt.Errorf("playbook %s: %w", path, err)
|
||||
}
|
||||
|
||||
actions, err := compileActions(path, raw.Actions, schemas)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pb.Actions = actions
|
||||
return pb, nil
|
||||
}
|
||||
|
||||
// compileActions validates the action shape (D2) and compiles every action's
|
||||
// expressions against that action's environment of prior results. Exactly one
|
||||
// workflow action is a workflow playbook; one or more module actions is an
|
||||
// action playbook; anything else fails the load naming the playbook.
|
||||
func compileActions(path string, raw []rawAction, schemas KindSchemas) ([]Action, error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, fmt.Errorf("playbook %s: must declare at least one action", path)
|
||||
}
|
||||
|
||||
var workflows, modules int
|
||||
for i := range raw {
|
||||
a := &raw[i]
|
||||
pos := strings.TrimSpace(a.Position)
|
||||
if pos == "" {
|
||||
// Default position for a single bare workflow name stays workflow
|
||||
// for the smallest-useful case.
|
||||
if len(raw) == 1 && strings.TrimSpace(a.Workflow) != "" {
|
||||
pos = "workflow"
|
||||
} else {
|
||||
return nil, fmt.Errorf("playbook %s: action %d must declare a position (%q or %q)", path, i+1, "workflow", "module")
|
||||
}
|
||||
}
|
||||
if pos != "workflow" && pos != "module" {
|
||||
return nil, fmt.Errorf("playbook %s: action %d position %q is not supported (want %q or %q)", path, i+1, pos, "workflow", "module")
|
||||
}
|
||||
a.Position = pos
|
||||
if pos == "workflow" {
|
||||
workflows++
|
||||
} else {
|
||||
modules++
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case workflows > 0 && modules > 0:
|
||||
return nil, fmt.Errorf("playbook %s: cannot mix workflow and module actions in one playbook", path)
|
||||
case workflows > 0:
|
||||
if workflows != 1 {
|
||||
return nil, fmt.Errorf("playbook %s: exactly one workflow action is supported; got %d", path, workflows)
|
||||
}
|
||||
return compileWorkflowActions(path, raw)
|
||||
default:
|
||||
return compileModuleActions(path, raw, schemas)
|
||||
}
|
||||
}
|
||||
|
||||
// compileWorkflowActions builds the single-action workflow playbook shape.
|
||||
// The env has no prior result ids, so a workflow `when` or `args` value that
|
||||
// reads `actions.<id>` fails at compile -- the unchanged workflow behaviour.
|
||||
func compileWorkflowActions(path string, raw []rawAction) ([]Action, error) {
|
||||
a := raw[0]
|
||||
if strings.TrimSpace(a.Workflow) == "" {
|
||||
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", path)
|
||||
}
|
||||
|
||||
env := expr.NewEnv()
|
||||
action := Action{
|
||||
Position: a.Position,
|
||||
Position: "workflow",
|
||||
ID: a.ID,
|
||||
Workflow: strings.TrimSpace(a.Workflow),
|
||||
env: env,
|
||||
}
|
||||
if strings.TrimSpace(a.When) != "" {
|
||||
prg, err := compileWhen(path, a.When, env, raw.Actions)
|
||||
prg, err := compileExpr(path, "when condition", a.When, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.When = prg
|
||||
}
|
||||
args, err := compileArgs(path, a.Args, env, raw.Actions)
|
||||
args, err := compileArgs(path, "", a.Args, env, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.Args = args
|
||||
pb.Actions = []Action{action}
|
||||
return pb, nil
|
||||
return []Action{action}, nil
|
||||
}
|
||||
|
||||
// compileWhen compiles a raw `when` expression and validates its action
|
||||
// references against the actions declared before it. The wording of the
|
||||
// returned errors is the loader's existing contract, preserved verbatim by
|
||||
// passing the `when condition` field label to compileExpr.
|
||||
func compileWhen(path, when string, env *expr.Env, prior []rawAction) (*expr.Program, error) {
|
||||
return compileExpr(path, "when condition", when, env, prior)
|
||||
// compileModuleActions builds the one-or-more-module-actions playbook shape.
|
||||
// Each action's env declares the prior actions' ids typed by their kinds'
|
||||
// Result structs, so a later action can read an earlier result and a forward
|
||||
// or field-typo read fails at compile (multi-action-playbooks.md, D3).
|
||||
func compileModuleActions(path string, raw []rawAction, schemas KindSchemas) ([]Action, error) {
|
||||
actions := make([]Action, 0, len(raw))
|
||||
var declared []expr.DeclaredResult
|
||||
for _, a := range raw {
|
||||
kind := strings.TrimSpace(a.Kind)
|
||||
if kind == "" {
|
||||
return nil, fmt.Errorf("playbook %s: module-kind action must name a kind", path)
|
||||
}
|
||||
argsType, resultType, ok := schemas.KindSchema(kind)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("playbook %s: unknown module kind %q", path, kind)
|
||||
}
|
||||
|
||||
env := expr.NewEnv(declared...)
|
||||
action := Action{
|
||||
Position: "module",
|
||||
ID: a.ID,
|
||||
Kind: kind,
|
||||
env: env,
|
||||
}
|
||||
if strings.TrimSpace(a.When) != "" {
|
||||
prg, err := compileExpr(path, "when condition", a.When, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.When = prg
|
||||
}
|
||||
args, err := compileArgs(path, kind, a.Args, env, argsType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.Args = args
|
||||
actions = append(actions, action)
|
||||
|
||||
if a.ID != "" {
|
||||
declared = append(declared, expr.DeclaredResult{ID: a.ID, Type: resultType})
|
||||
}
|
||||
}
|
||||
return actions, nil
|
||||
}
|
||||
|
||||
// compileArgs compiles every args value as a CEL expression at load, keyed by
|
||||
// arg name. J2 has no literal/expression split: the YAML scalar text IS the
|
||||
// CEL source, so a string literal is quoted inside YAML and a number or
|
||||
// context read is written as CEL. Each program goes through the same
|
||||
// context read is written as CEL. When argsSchema is non-nil (a module kind's
|
||||
// Args struct) every key must name one of its fields; workflow actions pass
|
||||
// nil and keep free-form args. Each program goes through the same
|
||||
// compile/reference validation as `when`, with the field label naming the
|
||||
// offending args key.
|
||||
func compileArgs(path string, raw map[string]string, env *expr.Env, prior []rawAction) (map[string]*expr.Program, error) {
|
||||
func compileArgs(path, kind string, raw map[string]string, env *expr.Env, argsSchema reflect.Type) (map[string]*expr.Program, error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if argsSchema != nil {
|
||||
if err := validateArgsKeys(path, kind, argsSchema, raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(raw))
|
||||
for key := range raw {
|
||||
keys = append(keys, key)
|
||||
@@ -300,7 +390,7 @@ func compileArgs(path string, raw map[string]string, env *expr.Env, prior []rawA
|
||||
sort.Strings(keys)
|
||||
args := make(map[string]*expr.Program, len(raw))
|
||||
for _, key := range keys {
|
||||
prg, err := compileExpr(path, fmt.Sprintf("args[%q]", key), raw[key], env, prior)
|
||||
prg, err := compileExpr(path, fmt.Sprintf("args[%q]", key), raw[key], env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -309,27 +399,47 @@ func compileArgs(path string, raw map[string]string, env *expr.Env, prior []rawA
|
||||
return args, nil
|
||||
}
|
||||
|
||||
// compileExpr compiles one playbook expression and applies the two load-time
|
||||
// reference checks: every `actions` read must be statically resolvable to a
|
||||
// prior action id, and every resolved id must be declared on an earlier
|
||||
// action. field is the human-readable expression location used in errors
|
||||
// (`when condition` or `args["name"]`), so a failure names the playbook path
|
||||
// and the offending expression.
|
||||
func compileExpr(path, field, src string, env *expr.Env, prior []rawAction) (*expr.Program, error) {
|
||||
// validateArgsKeys rejects an args key the kind's Args struct does not define
|
||||
// (multi-action-playbooks.md, D4), so an arg typo is a load failure rather
|
||||
// than a dispatch-time shape mismatch. Go field names are lower-cased to the
|
||||
// YAML spelling (Message -> message), matching the module's strict decode.
|
||||
func validateArgsKeys(path, kind string, argsSchema reflect.Type, raw map[string]string) error {
|
||||
t := argsSchema
|
||||
if t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
fields := make(map[string]struct{}, t.NumField())
|
||||
for field := range t.Fields() {
|
||||
fields[strings.ToLower(field.Name)] = struct{}{}
|
||||
}
|
||||
for key := range raw {
|
||||
if _, ok := fields[strings.ToLower(key)]; !ok {
|
||||
return fmt.Errorf("playbook %s: %s kind args[%q] is not a declared Args field", path, kind, key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compileExpr compiles one playbook expression and applies the remaining
|
||||
// load-time reference check: every `actions` read must be statically
|
||||
// resolvable to a prior action id. The per-playbook object type rejects an
|
||||
// undeclared or forward id and a dynamic `actions` read at compile time; the
|
||||
// one spelling it does not reject is a bare `actions` value read, which this
|
||||
// check still refuses. field is the human-readable expression location used in
|
||||
// errors (`when condition` or `args["name"]`), so a failure names the
|
||||
// playbook path and the offending expression.
|
||||
func compileExpr(path, field, src string, env *expr.Env) (*expr.Program, error) {
|
||||
prg, err := env.Compile(strings.TrimSpace(src))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("playbook %s: %s: %w", path, field, err)
|
||||
}
|
||||
ids, resolvable := prg.ActionReferences()
|
||||
_, resolvable := prg.ActionReferences()
|
||||
if !resolvable {
|
||||
return nil, fmt.Errorf(
|
||||
"playbook %s: %s contains an `actions` reference that cannot be statically resolved to an action id (the `actions` context root must be read as a prior action id)",
|
||||
path, field,
|
||||
)
|
||||
}
|
||||
if id, unknown := unknownActionReference(prior, 0, ids); unknown {
|
||||
return nil, fmt.Errorf("playbook %s: %s references unknown action id %q", path, field, id)
|
||||
}
|
||||
return prg, nil
|
||||
}
|
||||
|
||||
@@ -401,8 +511,11 @@ type Decision struct {
|
||||
ActionPosition int
|
||||
}
|
||||
|
||||
// Dispatch returns the workflow name the first matching playbook selects for
|
||||
// the input, and whether any playbook matched. No match means trigger
|
||||
// Dispatch returns the workflow name the first matching workflow playbook
|
||||
// selects for the input, and whether any playbook matched. Action playbooks
|
||||
// are loaded and validated but not routed (multi-action-playbooks.md, D1), so
|
||||
// this considers workflow playbooks only: an action playbook cannot hijack the
|
||||
// definition pin before its run path exists (t2db.31). No match means trigger
|
||||
// mismatch or a when condition evaluating false, and the caller keeps its own
|
||||
// routing.
|
||||
//
|
||||
@@ -426,9 +539,13 @@ func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
|
||||
if !pb.Match(input) {
|
||||
continue
|
||||
}
|
||||
if len(pb.Actions) != 1 || pb.Actions[0].Position != "workflow" {
|
||||
// Action playbook: loaded and validated, not routed (D1).
|
||||
continue
|
||||
}
|
||||
a := pb.Actions[0]
|
||||
if a.When != nil {
|
||||
val, err := s.exprEnv.Eval(a.When, ctx)
|
||||
val, err := a.env.Eval(a.When, ctx)
|
||||
if err != nil {
|
||||
// J3: evaluation error -> false (skip), caller logs.
|
||||
continue
|
||||
@@ -479,7 +596,7 @@ func (s *Store) EvalArgs(a Action, input DispatchInput) (map[string]any, error)
|
||||
if a.Args[key] == nil {
|
||||
continue
|
||||
}
|
||||
val, err := s.exprEnv.Eval(a.Args[key], ctx)
|
||||
val, err := a.env.Eval(a.Args[key], ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("evaluate args[%q]: %w", key, err)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, dir, name, content string) string {
|
||||
@@ -24,6 +25,15 @@ func writeFile(t *testing.T, dir, name, content string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
// testSchemas is the real module kind-schema source the loader consults in
|
||||
// tests: *module.ModuleRegistry satisfies playbook.KindSchemas. It consults
|
||||
// the built-in kind registry, so no module file needs to be installed for the
|
||||
// schema lookup to work.
|
||||
func testSchemas(t *testing.T) KindSchemas {
|
||||
t.Helper()
|
||||
return module.New()
|
||||
}
|
||||
|
||||
// TestLoadSingleWorkflowActionRoundTrip: a playbook with trigger + one
|
||||
// workflow-kind action + optional when loads and dispatches to the correct
|
||||
// registered workflow when trigger+when match.
|
||||
@@ -37,7 +47,7 @@ actions:
|
||||
workflow: tdd
|
||||
when: event.priority == 3
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -78,7 +88,7 @@ actions:
|
||||
workflow: tdd
|
||||
when: event.priority == 5
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -105,32 +115,49 @@ actions:
|
||||
- position: workflow
|
||||
workflow: implement
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(2 actions) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exactly one action") {
|
||||
t.Errorf("Load error = %q, want the one-action rule named", err.Error())
|
||||
if !strings.Contains(err.Error(), "exactly one workflow action") {
|
||||
t.Errorf("Load error = %q, want the one-workflow-action rule named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadNonWorkflowPositionIsLoadFailure: a playbook with a non-workflow
|
||||
// action position is a reported load failure.
|
||||
func TestLoadNonWorkflowPositionIsLoadFailure(t *testing.T) {
|
||||
// TestLoadModuleActionIsValidActionPlaybook: one module action is now a valid
|
||||
// action playbook shape (one or more module actions in order).
|
||||
func TestLoadModuleActionIsValidActionPlaybook(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
- id: build
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"build started"'
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
if err == nil {
|
||||
t.Fatal("Load(module action) = nil, want load failure")
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load(module action) = %v, want a valid action playbook", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "workflow") {
|
||||
t.Errorf("Load error = %q, want the position restriction named", err.Error())
|
||||
if len(store.Playbooks) != 1 {
|
||||
t.Fatalf("loaded %d playbooks, want 1", len(store.Playbooks))
|
||||
}
|
||||
a := store.Playbooks[0].Actions[0]
|
||||
if a.Position != "module" || a.Kind != "log" {
|
||||
t.Errorf("action = (%q, %q), want (module, log)", a.Position, a.Kind)
|
||||
}
|
||||
if a.ID != "build" {
|
||||
t.Errorf("action id = %q, want build", a.ID)
|
||||
}
|
||||
if len(a.Args) != 1 || a.Args["message"] == nil {
|
||||
t.Errorf("Action.Args = %#v, want the message program compiled", a.Args)
|
||||
}
|
||||
// Action playbooks are loaded and validated but not routed (D1).
|
||||
if decision, ok := store.Dispatch(DispatchInput{Kind: "bug", Event: map[string]any{}}); ok {
|
||||
t.Fatalf("Dispatch(action playbook) = %v, want no match (not routed)", decision)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,7 +174,7 @@ actions:
|
||||
workflow: tdd
|
||||
when: event.label ==
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(bad when) = nil, want compile failure reported")
|
||||
}
|
||||
@@ -168,7 +195,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(no trigger) = nil, want load failure")
|
||||
}
|
||||
@@ -185,7 +212,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -210,7 +237,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -245,7 +272,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: implement
|
||||
`)
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(dir with one bad playbook) = nil, want whole-load failure")
|
||||
}
|
||||
@@ -254,7 +281,7 @@ actions:
|
||||
// TestLoadMissingDirIsEmptyStore: a nonexistent directory is an empty store
|
||||
// (no playbooks), matching the flat binding loaders' convention.
|
||||
func TestLoadMissingDirIsEmptyStore(t *testing.T) {
|
||||
store, err := Load(filepath.Join(t.TempDir(), "does-not-exist"))
|
||||
store, err := Load(filepath.Join(t.TempDir(), "does-not-exist"), testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load(missing dir) = %v, want nil", err)
|
||||
}
|
||||
@@ -276,7 +303,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -301,7 +328,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
storeA, err := Load(dir)
|
||||
storeA, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -310,7 +337,7 @@ actions:
|
||||
}
|
||||
|
||||
// Re-load unchanged content: identical version.
|
||||
storeB, err := Load(dir)
|
||||
storeB, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -327,7 +354,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: implement
|
||||
`)
|
||||
storeC, err := Load(dir)
|
||||
storeC, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -352,7 +379,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -377,7 +404,7 @@ actions:
|
||||
// the proof the shipped shape works, not just test fixtures.
|
||||
func TestShippedExamplePlaybookLoads(t *testing.T) {
|
||||
dir := filepath.Join("..", "..", "..", "..", "examples", "eda-playbooks")
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load(shipped example): %v", err)
|
||||
}
|
||||
@@ -441,7 +468,7 @@ actions:
|
||||
workflow: tdd
|
||||
id: notify
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -465,7 +492,7 @@ func TestLoadMalformedActionIDFails(t *testing.T) {
|
||||
t.Run(id, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n id: "+id+"\n")
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatalf("Load(id %q) = nil, want load failure", id)
|
||||
}
|
||||
@@ -474,8 +501,7 @@ func TestLoadMalformedActionIDFails(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestValidateActionIDs: the shape/uniqueness helper is the load-boundary's
|
||||
// id gate, unit-tested directly because the one-action boundary makes
|
||||
// duplicates unreachable through Load today.
|
||||
// id gate for both playbook shapes.
|
||||
func TestValidateActionIDs(t *testing.T) {
|
||||
if err := validateActionIDs([]rawAction{{ID: "notify"}, {ID: "notify"}}); err == nil {
|
||||
t.Fatal("validateActionIDs(duplicate) = nil, want error")
|
||||
@@ -510,7 +536,7 @@ func TestLoadWhenActionsReferenceFails(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: "+tc.when+"\n")
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load = nil, want load failure")
|
||||
}
|
||||
@@ -524,29 +550,6 @@ func TestLoadWhenActionsReferenceFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnknownActionReferenceGeneralRule: the reference check compares the
|
||||
// statically-resolved ids against the declared ids of earlier actions, so it
|
||||
// already behaves correctly when the one-action boundary later relaxes (the
|
||||
// Load path can only exercise the empty-prior set today). The ids are passed
|
||||
// directly: under the per-playbook object type an undeclared `actions.<id>`
|
||||
// read is rejected at compile time, so there is no longer an env that compiles
|
||||
// one to classify.
|
||||
func TestUnknownActionReferenceGeneralRule(t *testing.T) {
|
||||
// a declared on the prior action: known.
|
||||
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, []string{"a"}); unknown {
|
||||
t.Fatalf("unknownActionReference(declared prior) = (%q, true), want known", id)
|
||||
}
|
||||
// Two static reads of a in one expression resolve to the one declared id
|
||||
// (ActionReferences de-duplicates), so the de-duplicated id is known.
|
||||
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, []string{"a", "a"}); unknown {
|
||||
t.Fatalf("unknownActionReference(deduplicated declared id) = (%q, true), want known", id)
|
||||
}
|
||||
// A different prior id leaves b unknown.
|
||||
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, []string{"b"}); !unknown || id != "b" {
|
||||
t.Fatalf("unknownActionReference(undeclared) = (%q, %v), want (b, true)", id, unknown)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatchNilStoreMatchesNothing: a nil store is the state a composition
|
||||
// root is in before the playbook load runs, and callers hold it through an
|
||||
// interface where a typed nil is not a nil interface.
|
||||
@@ -574,7 +577,7 @@ actions:
|
||||
priority: '3'
|
||||
label: 'event.label'
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -672,7 +675,7 @@ actions:
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", tc.doc)
|
||||
_, err := Load(dir)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load = nil, want load failure")
|
||||
}
|
||||
@@ -695,7 +698,7 @@ func TestCompileArgsReportsFirstKeyDeterministically(t *testing.T) {
|
||||
"a.bad": "event.missing ==",
|
||||
}
|
||||
for range 64 {
|
||||
_, err := compileArgs("pb.yaml", raw, env, nil)
|
||||
_, err := compileArgs("pb.yaml", "", raw, env, nil)
|
||||
if err == nil {
|
||||
t.Fatal("compileArgs = nil, want error")
|
||||
}
|
||||
@@ -721,7 +724,7 @@ actions:
|
||||
args:
|
||||
label: 'event.missing'
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -742,7 +745,7 @@ actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -769,7 +772,7 @@ actions:
|
||||
args:
|
||||
message: '"hello"'
|
||||
`)
|
||||
store, err := Load(dir)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
@@ -807,3 +810,264 @@ func TestEvalArgsNilStoreSafe(t *testing.T) {
|
||||
t.Fatalf("EvalArgs(nil store) = %#v, want empty non-nil map", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookReadsPriorResult: a later module action reads an
|
||||
// earlier action's declared result by its kind-typed Result field, so the
|
||||
// per-action environment (D3) must declare prior ids. This is the first new
|
||||
// test that fails if the loader compiled every action against one env instead
|
||||
// of an env built from the prior actions' ids.
|
||||
func TestLoadActionPlaybookReadsPriorResult(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- id: build
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"build started"'
|
||||
- id: done
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"done"'
|
||||
when: actions.build.result.written == true
|
||||
`)
|
||||
store, err := Load(dir, testSchemas(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Load(action playbook reading a prior result): %v", err)
|
||||
}
|
||||
pb := store.Playbooks[0]
|
||||
if len(pb.Actions) != 2 {
|
||||
t.Fatalf("loaded %d actions, want 2", len(pb.Actions))
|
||||
}
|
||||
if pb.Actions[1].When == nil {
|
||||
t.Fatal("second action when = nil, want the compiled prior-result read")
|
||||
}
|
||||
if pb.Actions[1].Args["message"] == nil {
|
||||
t.Fatal("second action args[message] = nil, want a compiled program")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookForwardReferenceFails: an action may not read a later
|
||||
// action's id -- the env only declares PRIOR actions' ids, so the forward read
|
||||
// is an undefined field at compile.
|
||||
func TestLoadActionPlaybookForwardReferenceFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"first"'
|
||||
when: actions.done.result.written == true
|
||||
- id: done
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"second"'
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(forward reference) = nil, want load failure")
|
||||
}
|
||||
for _, want := range []string{"pb.yaml", "done"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("Load error = %q, want it to name %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsUnknownKind: an action's kind must name a
|
||||
// registered module kind.
|
||||
func TestLoadActionPlaybookRejectsUnknownKind(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: notify
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(unknown kind) = nil, want load failure")
|
||||
}
|
||||
for _, want := range []string{"pb.yaml", "notify"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("Load error = %q, want it to name %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsMissingKind: a module action must name a kind.
|
||||
func TestLoadActionPlaybookRejectsMissingKind(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(missing kind) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Errorf("Load error = %q, want the playbook path named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsUnsupportedPosition: a position other than
|
||||
// workflow or module is a load failure naming the playbook.
|
||||
func TestLoadActionPlaybookRejectsUnsupportedPosition(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: channel
|
||||
kind: log
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(channel position) = nil, want load failure")
|
||||
}
|
||||
for _, want := range []string{"pb.yaml", "channel"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("Load error = %q, want it to name %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsMixedPositions: workflow and module actions
|
||||
// never mix in one playbook (D2).
|
||||
func TestLoadActionPlaybookRejectsMixedPositions(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
- position: module
|
||||
kind: log
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(mixed positions) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Errorf("Load error = %q, want the playbook path named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsZeroActions: a playbook must declare at least
|
||||
// one action.
|
||||
func TestLoadActionPlaybookRejectsZeroActions(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions: []
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(zero actions) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Errorf("Load error = %q, want the playbook path named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsDuplicateIDs: duplicate ids are reachable once
|
||||
// action playbooks are loadable, and the shared id gate rejects them.
|
||||
func TestLoadActionPlaybookRejectsDuplicateIDs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- id: build
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"first"'
|
||||
- id: build
|
||||
position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"second"'
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(duplicate ids) = nil, want load failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "duplicate action id") {
|
||||
t.Errorf("Load error = %q, want the duplicate-id rule named", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsUnknownArgKey: an args key the kind's Args
|
||||
// struct does not define fails the load (D4).
|
||||
func TestLoadActionPlaybookRejectsUnknownArgKey(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"hello"'
|
||||
bogus: '"x"'
|
||||
`)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load(unknown arg key) = nil, want load failure")
|
||||
}
|
||||
for _, want := range []string{"pb.yaml", "bogus"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("Load error = %q, want it to name %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadActionPlaybookRejectsActionReferences is the classifier-enumeration
|
||||
// proof (E): every `actions` spelling the old classifier rejected must still
|
||||
// be rejected for a typed action playbook. All but the bare `actions` value
|
||||
// are rejected by CEL's per-playbook object type at compile; the bare value
|
||||
// read is the one spelling CEL does not reject, kept behind the retained
|
||||
// resolvable check in expr.ActionReferences.
|
||||
func TestLoadActionPlaybookRejectsActionReferences(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
when string
|
||||
}{
|
||||
{name: "unknown id", when: `actions.missing.result.written == true`},
|
||||
{name: "literal map index", when: `actions["build"].result.written == true`},
|
||||
{name: "computed index", when: `actions[key].result.written == true`},
|
||||
{name: "dynamic index by event", when: `actions[event.name].result.written == true`},
|
||||
{name: "in operator", when: `"build" in actions`},
|
||||
{name: "size", when: `size(actions) > 0`},
|
||||
{name: "method call", when: `actions.all(x, true)`},
|
||||
{name: "equality with map", when: `actions == {}`},
|
||||
{name: "bare actions", when: `actions`},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build started\"'\n - id: done\n position: module\n kind: log\n args:\n message: '\"done\"'\n when: "+tc.when+"\n")
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatalf("Load(%s) = nil, want load failure", tc.when)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Errorf("Load error = %q, want the playbook path named", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user