Feat v0.9.8 routing sdk (#82)
Some checks failed
CI/CD / detect-changes (push) Successful in 4s
CI/CD / test-frontend (push) Has been skipped
CI/CD / test-runners (push) Has been skipped
CI/CD / e2e-smoke (push) Has been skipped
CI/CD / test-go-pg (push) Failing after 2m39s
CI/CD / test-sqlite (push) Successful in 3m0s
CI/CD / build-and-deploy (push) Has been skipped
Some checks failed
CI/CD / detect-changes (push) Successful in 4s
CI/CD / test-frontend (push) Has been skipped
CI/CD / test-runners (push) Has been skipped
CI/CD / e2e-smoke (push) Has been skipped
CI/CD / test-go-pg (push) Failing after 2m39s
CI/CD / test-sqlite (push) Successful in 3m0s
CI/CD / build-and-deploy (push) Has been skipped
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #82.
This commit is contained in:
21
CHANGELOG.md
21
CHANGELOG.md
@@ -2,6 +2,27 @@
|
||||
|
||||
All notable changes to Armature are documented here.
|
||||
|
||||
## v0.9.8 — Conditional Routing → SDK Primitive
|
||||
|
||||
Promotes the workflow branch-rule engine to a generic Starlark SDK
|
||||
module available to all extensions — no permission required.
|
||||
|
||||
**New Starlark module: `routing`**
|
||||
|
||||
- `routing.evaluate(rules, data)` — evaluates an ordered list of
|
||||
condition rules against a data dict; returns the first matching
|
||||
rule's `target` string, or `None` if no rule matches
|
||||
- 10 operators: `exists`, `not_exists`, `eq`, `neq`, `gt`, `lt`,
|
||||
`gte`, `lte`, `in`, `contains`
|
||||
- First-match-wins semantics
|
||||
- Domain-agnostic: uses `target` (not `target_stage`) so any
|
||||
extension can use it for feature flags, content routing, approval
|
||||
logic, etc.
|
||||
- Always available — pure computation, no I/O, no permission gate
|
||||
|
||||
**Tests:** 8 new unit tests covering all operators, type coercion,
|
||||
first-match-wins, empty/missing/bad input
|
||||
|
||||
## v0.9.7 — Full Read/Write Workflow Starlark Module
|
||||
|
||||
Extensions with `workflow.access` permission can now start, advance,
|
||||
|
||||
@@ -137,10 +137,13 @@ circular import. Four write builtins added: `workflow.start()`,
|
||||
`instanceToDict` and `signoffToDict` helpers shared by read+write paths.
|
||||
6 new tests.
|
||||
|
||||
**v0.9.8 — Conditional Routing → SDK Primitive**
|
||||
**v0.9.8 — Conditional Routing → SDK Primitive** *(completed)*
|
||||
|
||||
Expose `routing.evaluate(rules, data)` as a Starlark SDK function.
|
||||
Branch rules become a reusable decision engine for any extension.
|
||||
`routing.evaluate(rules, data)` Starlark builtin — a generic decision
|
||||
engine reusable by any extension. 10 operators (exists, not_exists, eq,
|
||||
neq, gt, lt, gte, lte, in, contains), first-match-wins, returns target
|
||||
string or None. Always available (pure computation, no permission).
|
||||
8 new tests.
|
||||
|
||||
**v0.9.9 — Surface Access via Roles**
|
||||
|
||||
|
||||
@@ -84,6 +84,24 @@ Returns `True` if the user has the permission, `False` otherwise (including
|
||||
when the user is not found). Resolves the user's groups and merges granted
|
||||
permissions — works for both kernel and extension-declared permissions.
|
||||
|
||||
### routing
|
||||
|
||||
Generic rule-based decision engine. Evaluates an ordered list of conditions
|
||||
against a data dict, returning the first matching rule's target string.
|
||||
|
||||
```python
|
||||
result = routing.evaluate([
|
||||
{"field": "priority", "op": "eq", "value": "critical", "target": "escalation"},
|
||||
{"field": "amount", "op": "gt", "value": 10000, "target": "manager_review"},
|
||||
{"field": "region", "op": "in", "value": ["EU", "UK"], "target": "gdpr_flow"},
|
||||
], stage_data)
|
||||
# Returns "escalation", "manager_review", "gdpr_flow", or None
|
||||
```
|
||||
|
||||
Each rule is a dict with `field`, `op`, `value`, and `target`. Operators:
|
||||
`exists`, `not_exists`, `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, `in`,
|
||||
`contains`. First-match-wins; returns `None` if no rule matches.
|
||||
|
||||
## Permission-gated modules
|
||||
|
||||
These modules are only available if the package has the corresponding
|
||||
|
||||
190
server/sandbox/routing_module.go
Normal file
190
server/sandbox/routing_module.go
Normal file
@@ -0,0 +1,190 @@
|
||||
package sandbox
|
||||
|
||||
// routing_module.go
|
||||
//
|
||||
// Starlark routing module — a generic rule-based decision engine.
|
||||
// Always available (pure computation, no I/O).
|
||||
//
|
||||
// Starlark API:
|
||||
// result = routing.evaluate(rules, data)
|
||||
// # result → "target_string" or None
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"go.starlark.net/starlark"
|
||||
"go.starlark.net/starlarkstruct"
|
||||
)
|
||||
|
||||
// BuildRoutingModule creates the "routing" Starlark module.
|
||||
// No permission required — pure computation.
|
||||
func BuildRoutingModule() *starlarkstruct.Module {
|
||||
return MakeModule("routing", starlark.StringDict{
|
||||
"evaluate": starlark.NewBuiltin("routing.evaluate", routingEvaluateBuiltin()),
|
||||
})
|
||||
}
|
||||
|
||||
// routingRule is the generic equivalent of workflow.Condition.
|
||||
// Uses "target" instead of "target_stage" to be domain-agnostic.
|
||||
type routingRule struct {
|
||||
Field string
|
||||
Op string
|
||||
Value any
|
||||
Target string
|
||||
}
|
||||
|
||||
func routingEvaluateBuiltin() func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
|
||||
return func(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
|
||||
var rulesVal, dataVal starlark.Value
|
||||
if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 2, &rulesVal, &dataVal); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Convert rules list → []routingRule
|
||||
rulesList, ok := rulesVal.(*starlark.List)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("routing.evaluate: rules must be a list, got %s", rulesVal.Type())
|
||||
}
|
||||
|
||||
rules := make([]routingRule, rulesList.Len())
|
||||
for i := 0; i < rulesList.Len(); i++ {
|
||||
ruleDict, ok := rulesList.Index(i).(*starlark.Dict)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("routing.evaluate: rules[%d] must be a dict, got %s", i, rulesList.Index(i).Type())
|
||||
}
|
||||
m := DictToMap(ruleDict)
|
||||
|
||||
field, _ := m["field"].(string)
|
||||
op, _ := m["op"].(string)
|
||||
target, _ := m["target"].(string)
|
||||
if field == "" || op == "" || target == "" {
|
||||
return nil, fmt.Errorf("routing.evaluate: rules[%d] must have field, op, and target", i)
|
||||
}
|
||||
rules[i] = routingRule{
|
||||
Field: field,
|
||||
Op: op,
|
||||
Value: m["value"],
|
||||
Target: target,
|
||||
}
|
||||
}
|
||||
|
||||
// Convert data dict → Go map
|
||||
dataDict, ok := dataVal.(*starlark.Dict)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("routing.evaluate: data must be a dict, got %s", dataVal.Type())
|
||||
}
|
||||
data := DictToMap(dataDict)
|
||||
|
||||
// Evaluate rules — first match wins
|
||||
for _, rule := range rules {
|
||||
if evaluateRoutingCondition(rule, data) {
|
||||
return starlark.String(rule.Target), nil
|
||||
}
|
||||
}
|
||||
|
||||
return starlark.None, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ── Evaluation helpers (mirrored from workflow/routing.go) ─────────
|
||||
//
|
||||
// These are pure functions copied from the workflow package to avoid
|
||||
// a sandbox → workflow import cycle. The workflow package continues
|
||||
// using its own copy for ResolveNextStage.
|
||||
|
||||
// evaluateRoutingCondition checks if a single rule matches against data.
|
||||
func evaluateRoutingCondition(rule routingRule, data map[string]any) bool {
|
||||
val, exists := data[rule.Field]
|
||||
|
||||
switch rule.Op {
|
||||
case "exists":
|
||||
return exists
|
||||
case "not_exists":
|
||||
return !exists
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
|
||||
switch rule.Op {
|
||||
case "eq":
|
||||
return routingCompareEq(val, rule.Value)
|
||||
case "neq":
|
||||
return !routingCompareEq(val, rule.Value)
|
||||
case "gt":
|
||||
return routingCompareNum(val, rule.Value) > 0
|
||||
case "lt":
|
||||
return routingCompareNum(val, rule.Value) < 0
|
||||
case "gte":
|
||||
return routingCompareNum(val, rule.Value) >= 0
|
||||
case "lte":
|
||||
return routingCompareNum(val, rule.Value) <= 0
|
||||
case "in":
|
||||
return routingCompareIn(val, rule.Value)
|
||||
case "contains":
|
||||
return routingCompareContains(val, rule.Value)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func routingCompareEq(a, b any) bool {
|
||||
return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
|
||||
}
|
||||
|
||||
func routingCompareNum(a, b any) int {
|
||||
af := routingToFloat(a)
|
||||
bf := routingToFloat(b)
|
||||
if af == nil || bf == nil {
|
||||
return 0
|
||||
}
|
||||
switch {
|
||||
case *af < *bf:
|
||||
return -1
|
||||
case *af > *bf:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func routingToFloat(v any) *float64 {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return &n
|
||||
case int:
|
||||
f := float64(n)
|
||||
return &f
|
||||
case int64:
|
||||
f := float64(n)
|
||||
return &f
|
||||
case string:
|
||||
var f float64
|
||||
if _, err := fmt.Sscanf(n, "%f", &f); err == nil {
|
||||
return &f
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func routingCompareIn(val, list any) bool {
|
||||
arr, ok := list.([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
vs := fmt.Sprintf("%v", val)
|
||||
for _, item := range arr {
|
||||
if fmt.Sprintf("%v", item) == vs {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func routingCompareContains(val, target any) bool {
|
||||
s := fmt.Sprintf("%v", val)
|
||||
t := fmt.Sprintf("%v", target)
|
||||
return strings.Contains(s, t)
|
||||
}
|
||||
162
server/sandbox/routing_module_test.go
Normal file
162
server/sandbox/routing_module_test.go
Normal file
@@ -0,0 +1,162 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"go.starlark.net/starlark"
|
||||
)
|
||||
|
||||
func runRoutingScript(t *testing.T, script string) starlark.StringDict {
|
||||
t.Helper()
|
||||
mod := BuildRoutingModule()
|
||||
predeclared := starlark.StringDict{"routing": mod}
|
||||
globals, err := starlark.ExecFile(&starlark.Thread{Name: "test"}, "test.star", script, predeclared)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return globals
|
||||
}
|
||||
|
||||
func runRoutingScriptErr(t *testing.T, script string) error {
|
||||
t.Helper()
|
||||
mod := BuildRoutingModule()
|
||||
predeclared := starlark.StringDict{"routing": mod}
|
||||
_, err := starlark.ExecFile(&starlark.Thread{Name: "test"}, "test.star", script, predeclared)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_SingleMatch(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
result = routing.evaluate([
|
||||
{"field": "priority", "op": "eq", "value": "high", "target": "escalation"},
|
||||
], {"priority": "high"})
|
||||
`)
|
||||
result := globals["result"]
|
||||
if s, ok := result.(starlark.String); !ok || string(s) != "escalation" {
|
||||
t.Fatalf("expected 'escalation', got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_FirstMatchWins(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
result = routing.evaluate([
|
||||
{"field": "amount", "op": "gt", "value": 100, "target": "big"},
|
||||
{"field": "amount", "op": "gt", "value": 50, "target": "medium"},
|
||||
], {"amount": 200})
|
||||
`)
|
||||
result := globals["result"]
|
||||
if s, ok := result.(starlark.String); !ok || string(s) != "big" {
|
||||
t.Fatalf("expected 'big', got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_NoMatch(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
result = routing.evaluate([
|
||||
{"field": "status", "op": "eq", "value": "done", "target": "finish"},
|
||||
], {"status": "pending"})
|
||||
`)
|
||||
if globals["result"] != starlark.None {
|
||||
t.Fatalf("expected None, got %v", globals["result"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_EmptyRules(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
result = routing.evaluate([], {"x": 1})
|
||||
`)
|
||||
if globals["result"] != starlark.None {
|
||||
t.Fatalf("expected None, got %v", globals["result"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_AllOperators(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
# exists
|
||||
r1 = routing.evaluate([{"field": "x", "op": "exists", "value": "", "target": "yes"}], {"x": 1})
|
||||
# not_exists
|
||||
r2 = routing.evaluate([{"field": "x", "op": "not_exists", "value": "", "target": "yes"}], {"y": 1})
|
||||
# eq
|
||||
r3 = routing.evaluate([{"field": "s", "op": "eq", "value": "abc", "target": "yes"}], {"s": "abc"})
|
||||
# neq
|
||||
r4 = routing.evaluate([{"field": "s", "op": "neq", "value": "abc", "target": "yes"}], {"s": "xyz"})
|
||||
# gt
|
||||
r5 = routing.evaluate([{"field": "n", "op": "gt", "value": 10, "target": "yes"}], {"n": 20})
|
||||
# lt
|
||||
r6 = routing.evaluate([{"field": "n", "op": "lt", "value": 10, "target": "yes"}], {"n": 5})
|
||||
# gte
|
||||
r7 = routing.evaluate([{"field": "n", "op": "gte", "value": 10, "target": "yes"}], {"n": 10})
|
||||
# lte
|
||||
r8 = routing.evaluate([{"field": "n", "op": "lte", "value": 10, "target": "yes"}], {"n": 10})
|
||||
# in
|
||||
r9 = routing.evaluate([{"field": "s", "op": "in", "value": ["a", "b", "c"], "target": "yes"}], {"s": "b"})
|
||||
# contains
|
||||
r10 = routing.evaluate([{"field": "s", "op": "contains", "value": "ell", "target": "yes"}], {"s": "hello"})
|
||||
`)
|
||||
for _, name := range []string{"r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10"} {
|
||||
v := globals[name]
|
||||
if s, ok := v.(starlark.String); !ok || string(s) != "yes" {
|
||||
t.Errorf("%s: expected 'yes', got %v", name, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_TypeCoercion(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
# Numeric string vs int
|
||||
r1 = routing.evaluate([
|
||||
{"field": "n", "op": "gt", "value": 10, "target": "yes"},
|
||||
], {"n": "20"})
|
||||
|
||||
# Int equality via string normalization
|
||||
r2 = routing.evaluate([
|
||||
{"field": "n", "op": "eq", "value": 42, "target": "yes"},
|
||||
], {"n": 42})
|
||||
`)
|
||||
for _, name := range []string{"r1", "r2"} {
|
||||
v := globals[name]
|
||||
if s, ok := v.(starlark.String); !ok || string(s) != "yes" {
|
||||
t.Errorf("%s: expected 'yes', got %v", name, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_BadInput(t *testing.T) {
|
||||
// rules must be a list
|
||||
err1 := runRoutingScriptErr(t, `routing.evaluate("bad", {})`)
|
||||
if err1 == nil {
|
||||
t.Fatal("expected error for non-list rules")
|
||||
}
|
||||
|
||||
// data must be a dict
|
||||
err2 := runRoutingScriptErr(t, `routing.evaluate([], "bad")`)
|
||||
if err2 == nil {
|
||||
t.Fatal("expected error for non-dict data")
|
||||
}
|
||||
|
||||
// rule missing required fields
|
||||
err3 := runRoutingScriptErr(t, `routing.evaluate([{"field": "x"}], {})`)
|
||||
if err3 == nil {
|
||||
t.Fatal("expected error for incomplete rule")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingEvaluate_MissingFields(t *testing.T) {
|
||||
globals := runRoutingScript(t, `
|
||||
# Field not in data — eq should not match
|
||||
r1 = routing.evaluate([
|
||||
{"field": "absent", "op": "eq", "value": "x", "target": "bad"},
|
||||
], {"other": "y"})
|
||||
|
||||
# not_exists matches when field is absent
|
||||
r2 = routing.evaluate([
|
||||
{"field": "absent", "op": "not_exists", "value": "", "target": "good"},
|
||||
], {"other": "y"})
|
||||
`)
|
||||
if globals["r1"] != starlark.None {
|
||||
t.Fatalf("r1: expected None for missing field, got %v", globals["r1"])
|
||||
}
|
||||
if s, ok := globals["r2"].(starlark.String); !ok || string(s) != "good" {
|
||||
t.Fatalf("r2: expected 'good', got %v", globals["r2"])
|
||||
}
|
||||
}
|
||||
@@ -467,6 +467,9 @@ func (r *Runner) buildModulesWithLibCtx(ctx context.Context, packageID string, m
|
||||
// Always available — read-only team role queries
|
||||
modules["teams"] = BuildTeamsModule(ctx, r.stores)
|
||||
|
||||
// Always available — pure-computation routing decision engine
|
||||
modules["routing"] = BuildRoutingModule()
|
||||
|
||||
// Allows any starlark package to load declared library dependencies.
|
||||
if lc != nil {
|
||||
modules["lib"] = BuildLibModule(ctx, r, packageID, rc, lc)
|
||||
|
||||
Reference in New Issue
Block a user