Seventh slice of docs/prds/eda-playbook-engine.md (t2db.15), consuming
t2db.14's expr package: the rich trigger+actions playbook document and
the coordinator that dispatches it.
- internal/domain/eda/playbook: Load(dir) reads *.yaml/*.yml playbook
documents (trigger + exactly one workflow-kind action + optional CEL
when), validating the HARD BOUNDARY at load: a playbook with 2+ actions
or a non-workflow action position is a reported load failure --
multi-action and Module/Channel/Forge actions stay blocked on the
unresolved execution-time gaps. Any malformed YAML, invalid trigger,
missing workflow name, or when compile failure fails the WHOLE load
(reject-at-load, same shape as routing collisions); a missing dir is an
empty store. Trigger reuses the existing workintake kind/label
vocabulary (no second label-matching mechanism). Dispatch matches
trigger, evaluates when (CEL, event context with actions: {} -- no
prior actions in single-action playbooks), and returns the named
workflow from the registry via the same lookup Route() uses -- no
duplicated dispatch logic. when eval error follows the resolved doc's
J3: false, skip, caller logs.
- Store.Dispatch(reg, DispatchInput) is the coordinator entrypoint; input
carries Labels/Kind/Event. Production task intake wiring
(daemon.go/pollNATS/publishTask) is explicitly NOT in this ticket -- a
follow-up; proven end to end via direct tests plus the shipped example
(examples/eda-playbooks/bug-tdd.yaml) loaded and dispatched through the
real path.
- Config: EDAPlaybookDir (eda_playbook_dir), documented as DISTINCT from
PlaybookDirs (flat binding files) -- a reader cannot confuse the two.
- Bootstrap: playbook.Load wired in loadWorkflows, log-and-abort on
failure matching every prior slice; nonexistent dir is an empty store.
- workflow.Route(), workflowForLabels, and the t2db.9-.12 binding loaders
are UNTOUCHED (verified: their full test suites pass, zero regressions).
Also carries small lint cleanups on t2db.13/.14 code flagged by the gate
run: expr Eval no longer type-asserts to ref.Val (Eval returns ref.Val
directly in v0.32.0; cel-go's own Eval wraps evaluation in recover --
verified in source); module decodeLogArgs extracted to clear the nestif
finding. golangci-lint: 0 issues.
Tests (10): single-action round trip, when-false skip, 2-action load
failure, non-workflow position load failure, when compile failure drops
playbook, empty trigger load failure, trigger mismatch skip, no-when
match, one-invalid-file fails whole load, missing dir empty store, plus
the shipped example load+dispatch. task check clean (113/113 UI, exit 0).
264 lines
8.0 KiB
Go
264 lines
8.0 KiB
Go
// 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 (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.
|
|
//
|
|
// This is an ADDITIONAL loading path alongside the flat kind/label binding
|
|
// files (t2db.9/.10/.11). workflow.Route() and the existing binding loaders
|
|
// are untouched; migrating Route() onto this mechanism is a separate, later
|
|
// decision.
|
|
package playbook
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
|
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
|
)
|
|
|
|
// 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.
|
|
type Playbook struct {
|
|
Trigger Trigger
|
|
Actions []Action
|
|
}
|
|
|
|
// Trigger decides which incoming events this playbook matches. It reuses the
|
|
// existing workintake label/kind vocabulary -- no second label-matching
|
|
// mechanism is invented here.
|
|
type Trigger struct {
|
|
// Kind is the routing kind (bug/feature/bootstrap); empty matches the
|
|
// default (unlabelled) flow.
|
|
Kind workintake.Kind
|
|
// Labels is the closed label set this trigger matches; an empty set
|
|
// matches any labels.
|
|
Labels []string
|
|
}
|
|
|
|
// Action is one step in a playbook. Exactly one action per playbook in this
|
|
// slice, position MUST be "workflow".
|
|
type Action struct {
|
|
Position string
|
|
// Workflow is the named workflow.Registry entry to dispatch to
|
|
// (position: workflow only).
|
|
Workflow string
|
|
// When is a compiled CEL condition; nil means unconditional.
|
|
When *expr.Program
|
|
}
|
|
|
|
// rawPlaybook is the YAML document shape before compilation.
|
|
type rawPlaybook struct {
|
|
Trigger rawTrigger `yaml:"trigger"`
|
|
Actions []rawAction `yaml:"actions"`
|
|
}
|
|
|
|
type rawTrigger struct {
|
|
Kind string `yaml:"kind"`
|
|
Labels []string `yaml:"labels"`
|
|
}
|
|
|
|
type rawAction struct {
|
|
Position string `yaml:"position"`
|
|
Workflow string `yaml:"workflow"`
|
|
Kind string `yaml:"kind"`
|
|
When string `yaml:"when"`
|
|
}
|
|
|
|
// Load reads every *.yaml/*.yml playbook in dir, validates each against the
|
|
// hard boundary (exactly one action, position workflow), and compiles each
|
|
// when expression. ANY failure -- malformed YAML, a multi-action playbook, a
|
|
// non-workflow position, a when 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) {
|
|
entries, err := os.ReadDir(dir)
|
|
if os.IsNotExist(err) {
|
|
return &Store{exprEnv: expr.NewEnv()}, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read playbook dir %s: %w", dir, err)
|
|
}
|
|
|
|
var names []string
|
|
for _, e := range entries {
|
|
if e.IsDir() {
|
|
continue
|
|
}
|
|
if ext := strings.ToLower(filepath.Ext(e.Name())); ext == ".yaml" || ext == ".yml" {
|
|
names = append(names, e.Name())
|
|
}
|
|
}
|
|
sort.Strings(names)
|
|
|
|
store := &Store{exprEnv: expr.NewEnv()}
|
|
for _, name := range names {
|
|
path := filepath.Join(dir, name)
|
|
pb, err := loadOne(path, store.exprEnv)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
store.Playbooks = append(store.Playbooks, pb)
|
|
}
|
|
return store, nil
|
|
}
|
|
|
|
// loadOne loads and validates a single playbook file.
|
|
func loadOne(path string, env *expr.Env) (*Playbook, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read playbook %s: %w", path, err)
|
|
}
|
|
var raw rawPlaybook
|
|
if err := yaml.Unmarshal(data, &raw); err != nil {
|
|
return nil, fmt.Errorf("parse playbook %s: %w", path, err)
|
|
}
|
|
|
|
pb := &Playbook{
|
|
Trigger: Trigger{
|
|
Kind: workintake.Kind(strings.TrimSpace(raw.Trigger.Kind)),
|
|
Labels: raw.Trigger.Labels,
|
|
},
|
|
}
|
|
|
|
if pb.Trigger.Kind == "" && len(raw.Trigger.Labels) == 0 {
|
|
return nil, fmt.Errorf("playbook %s: trigger must declare a kind or labels", path)
|
|
}
|
|
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)
|
|
}
|
|
|
|
action := Action{
|
|
Position: a.Position,
|
|
Workflow: strings.TrimSpace(a.Workflow),
|
|
}
|
|
if strings.TrimSpace(a.When) != "" {
|
|
prg, err := env.Compile(strings.TrimSpace(a.When))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("playbook %s: when condition: %w", path, err)
|
|
}
|
|
action.When = prg
|
|
}
|
|
pb.Actions = []Action{action}
|
|
return pb, nil
|
|
}
|
|
|
|
// DispatchInput is what the coordinator evaluates a playbook against at
|
|
// dispatch time.
|
|
type DispatchInput struct {
|
|
// Labels are the incoming task's labels (comma-split already).
|
|
Labels []string
|
|
// Kind is the routing kind the labels produced (workintake.KindForLabels).
|
|
Kind string
|
|
// Event is the event payload exposed as `event` in CEL expressions. For
|
|
// a workflow-kind dispatch this carries the label/kind fields cheaply
|
|
// available at this point.
|
|
Event map[string]any
|
|
}
|
|
|
|
// Match reports whether the playbook's trigger matches the input's labels.
|
|
func (pb *Playbook) Match(input DispatchInput) bool {
|
|
labels := input.Labels
|
|
if len(labels) == 0 {
|
|
labels = []string{}
|
|
}
|
|
kind := workintake.Kind(input.Kind)
|
|
|
|
if pb.Trigger.Kind != "" && pb.Trigger.Kind != kind {
|
|
return false
|
|
}
|
|
if len(pb.Trigger.Labels) > 0 {
|
|
// Trigger labels must all be present in the input's labels.
|
|
inputSet := make(map[string]bool, len(labels))
|
|
for _, l := range labels {
|
|
inputSet[strings.TrimSpace(l)] = true
|
|
}
|
|
for _, want := range pb.Trigger.Labels {
|
|
if !inputSet[strings.TrimSpace(want)] {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Dispatch returns the workflow to run for the input, or nil if no playbook
|
|
// matches (trigger mismatch or a when condition evaluating false). It reuses
|
|
// the named-workflow lookup that workflow.Route() uses -- it does not
|
|
// duplicate dispatch logic.
|
|
//
|
|
// A when evaluation error follows the resolved doc's J3: the condition
|
|
// evaluates to false and dispatch is skipped (the caller logs).
|
|
func (s *Store) Dispatch(reg workflow.Registry, input DispatchInput) *workflow.Workflow {
|
|
for _, pb := range s.Playbooks {
|
|
if !pb.Match(input) {
|
|
continue
|
|
}
|
|
a := pb.Actions[0]
|
|
if a.When != nil {
|
|
val, err := s.exprEnv.Eval(a.When, expr.Context{
|
|
Event: input.Event,
|
|
Actions: map[string]map[string]any{},
|
|
})
|
|
if err != nil {
|
|
// J3: evaluation error -> false (skip), caller logs.
|
|
continue
|
|
}
|
|
b, ok := val.(bool)
|
|
if !ok || !b {
|
|
continue
|
|
}
|
|
}
|
|
// Reuse the same named-workflow lookup Route() uses: this is the
|
|
// workflow.Registry map access, not a second dispatch path.
|
|
if wf, ok := reg[a.Workflow]; ok {
|
|
// Return a copy to keep the registry immutable from callers.
|
|
wfCopy := wf
|
|
return &wfCopy
|
|
}
|
|
// Requested workflow unavailable: reported as nil (the caller's
|
|
// Route()-equivalent handles the missing-workflow failure shape).
|
|
return nil
|
|
}
|
|
return nil
|
|
}
|