Skip to content

RuleFlows

A RuleFlow is a composable, executable pipeline that orchestrates Rules, RuleSets, nested RuleFlows, Functions, and Actions into a single flow — with typed input parameters, bindings, conditionals, loops, scopes, exception handling, and async execution built in.

import static org.rulii.model.function.Functions.function;
RuleFlow<BigDecimal> checkout = RuleFlow.builder()
.name("CheckoutFlow")
.description("Validates and prices an order")
.param("order", Order.class) // required input
.run(validationRules) // a RuleSet
.run(pricingRule, spec -> spec.as("price")) // a Rule; result bound as "price"
.<BigDecimal>returning(function((BigDecimal price) -> price))
.build();
BigDecimal price = checkout.run(order -> myOrder);

Every pipeline method returns the builder, so steps chain fluently and execute in declaration order. The name is required and must match [a-zA-Z$_][a-zA-Z0-9$_]*.

flow.run(); // no inputs
flow.run(orderId -> "A-1", amount -> 250); // BindingDeclaration lambdas
flow.run(bindings); // an existing Bindings instance
flow.run(ruleContext); // caller-supplied RuleContext
// Asynchronously — returns a CompletableFuture
CompletableFuture<BigDecimal> future = flow.runAsync(ruleContext);
CompletableFuture<BigDecimal> bounded = flow.runAsync(ruleContext, 10, TimeUnit.SECONDS);

The full set of builder commands:

Command Purpose
name(name) Flow name (required)
description(text) Optional human-readable description
category(name) / tags(...) (new in 2.1.0) Optional descriptive category ("Pricing/Discounts") and tags — never read at execution time; see Introspection & Metadata
context(configurator) Customize the RuleContext — must be the first step, once only
param(name, type, ...) Declare a required or optional input parameter, optionally with a default
bind(...) / bindTo(scope, ...) Add bindings to the current (or a named) scope
run(...) Run a Rule, RuleSet, nested RuleFlow, or a registry lookup by name/class
apply(function) Apply a Function; bind its result with spec.as(...)
execute(action) Execute a void side-effect Action
when(cond, then[, otherwise]) Conditional branch — bodies are Consumer<builder> lambdas
forEach(source, name[, stop], body) Iterate a collection; binds each element and a 0-based index
scope([name,] body) Run a body in a (named) binding scope; bindings are discarded afterwards
exit([extractor]) Terminate the flow immediately, optionally extracting a result
asyncRun(...) Launch a Rule/RuleSet/RuleFlow asynchronously; result is a CompletableFuture
await / awaitAll / awaitAny Block on one, all, or any of the named future bindings (default timeout 30s)
command(cmd) Inject a pre-built custom RuleFlowCommand
onException(type, body) Flow-level (global) exception handler
finalizer(action) Always runs after the pipeline — even on early exit or exception
returning([extractor]) Result extractor; no-arg form returns the RuleContext
build() Validate the pipeline structure and produce an immutable RuleFlow<T>

Parameters declared with param(...) are validated before the pipeline runs. A missing required parameter throws UnrulyException:

.param("orderId", String.class) // required
.param("notes", String.class, false) // optional
.param("discount", Integer.class,
function((RuleContext ctx) -> 5)) // default applied when absent
// With a description (new in 2.1.0) — recorded on the definition's InputParameter
.param("orderId", String.class, true, "The order to price")
.param("discount", Integer.class,
function((RuleContext ctx) -> 5), "Percent discount applied when absent")

(new in 2.1.0) Both forms take an optional trailing description — param(name, type, required, description) and param(name, type, defaultValue, description). The description is purely informational and lands on the flow definition’s InputParameter.

bind(...) adds bindings to the current scope; bindTo(scopeName, ...) targets a named scope. All the familiar loading styles from Bindings are available as steps:

.bind(total -> BigDecimal.ZERO) // BindingDeclaration lambda(s)
.bind("status", "pending") // explicit name + value
.bind(existingBindings) // copy from a Bindings instance
.bind(orderPojo) // JavaBean properties (or Map entries)
.bind(customLoader, sourceValue) // via a BindingLoader
.bindTo("audit", "checkedAt", Instant.now()) // same overloads, into scope "audit"

run(...) accepts a pre-built Rule, RuleSet, or nested RuleFlow — or a name / class resolved from the RuleRegistry at execution time:

.run(ageRule) // Rule
.run(eligibilityRules) // RuleSet
.run(pricingFlow) // nested RuleFlow
.run("CheckoutRuleSet") // RuleRegistry lookup by name
.run(FraudCheckRule.class) // RuleRegistry lookup by class

Overloads that take a spec consumer expose per-step configuration — there are no top-level as()/with() methods on the builder itself:

.run(pricingRule, spec -> spec
.as("price") // bind the step result into the current scope
.with(discount -> 0.1) // step-scoped params — exist only during the step
.onException(Exception.class, // step-level exception handler
b -> b.run(fallbackPricingRule)))
  • as(bindingName) — bind the step’s result into the current scope; as(scopeName, bindingName) targets a named scope.
  • with(...) — step-scoped parameters from BindingDeclaration lambdas or a POJO / Map; removed when the step completes.
  • onException(type, body) — a handler checked before the flow-level handler.
// apply() — evaluate a Function and use its result in later steps
.apply(function((BigDecimal price, Integer qty) -> price.multiply(BigDecimal.valueOf(qty))),
spec -> spec.as("total"))
// execute() — a void side effect; ExecuteSpec supports onException() only
.execute(action((BigDecimal total) -> log.info("total = {}", total)))

Container commands take Consumer<builder> bodies — the lambda itself delimits the block, so there is no endWhen() or endScope():

// Branching — otherwise-branch is optional
.when(condition((BigDecimal total) -> total.compareTo(threshold) > 0),
b -> b.run(premiumRules),
b -> b.run(standardRules))
// Iteration — binds each element as "item" and the 0-based position as "index"
.forEach(function((Order order) -> order.getLineItems()), "item",
b -> b.run(perLineItemRule))
// Iteration with an early-stop condition (checked after each element)
.forEach(sourceFn, "item", condition((Boolean done) -> done),
b -> b.run(perItemRule))
// Scoped bindings — discarded when the body ends
.scope("temp", b -> b
.bind(intermediate -> expensiveComputation())
.run(usesIntermediateRule))
// Early termination — subsequent top-level commands would fail build() as unreachable
.when(alreadyProcessed, b -> b.<String>exit(function(() -> "cached")))
// Result extraction — evaluated when the flow completes naturally
.<BigDecimal>returning(function((BigDecimal total) -> total))
// Always runs — success, early exit, or exception
.finalizer(action(() -> metrics.increment("checkout.flows")))

Use the type witness form .<String>returning(...) so build() infers RuleFlow<String>. The no-arg exit() and returning() forms return the RuleContext.

(new in 2.1.0) The returning(Class<T>, Function<T>) overload also states the result type explicitly — use it when the extractor’s declared return type isn’t specific enough (a script, or a generic lambda). The type is recorded on the RuleFlowDefinition and reported by getResultType().

A flow’s result type follows the same model as a RuleSet’s. RuleFlowDefinition.getResultType() keeps returning a Type — null for a flow that returns its RuleContext, and now also when the type cannot be told — and the new getResolvedResultType() returns an org.rulii.model.ResultType with its origin: DECLARED, DERIVED from the extractor, UNKNOWN for a script or generic-lambda extractor (it used to report Object), or NONE for a context flow.

// returning(Class, Function) — unchanged: states the type and the extractor together
.returning(BigDecimal.class, function((BigDecimal total) -> total))
// resultType(Type) — states the type on its own, for a script extractor ...
.resultType(BigDecimal.class)
.returning(Function.builder().build(Script.builder().build("js", "ctx.total")))
// ... or for a flow whose result comes from exit steps
.resultType(String.class)
.when(cached, b -> b.<String>exit(function(() -> "cached")))
.<String>returning(function((String outcome) -> outcome))
// Read it back
flow.getDefinition().getResolvedResultType().getOrigin(); // DECLARED
  • returning(Function) derives the type from the extractor and no longer drops a type stated before it; returning() still resets both, so the flow returns its context.
  • A stated type is checked at build(): no returning extractor in effect, or a returning or exit extractor whose declared return type it does not accept, is an UnrulyException naming the flow and both types. Exits are found through when, forEach, scope, async continuations and exception handlers.
  • A derived type never rejects a flow. Nothing is converted at run time; the type is a declaration, read by tools such as rulii-explorer and reported by toString().

Handlers exist at three levels: on a step, on an async step, and on the flow. Inside every handler body the caught exception is bound as "ex". What happens after the body has run depends on the level:

  • A step-level handler is catch-and-continue: the flow resumes at the next step.
  • A flow-level handler is catch-and-continue too (changed in 2.3.0): it recovers the failed step and the flow resumes with the next top-level step. A failure inside a when, forEach or scope leaves that container first, so the rest of the container is abandoned and the flow resumes with the step after it; to carry on inside the container, put the handler on the step. To stop the flow instead, end the handler body with exit().
// 1. Step-level — checked first
.run(riskyRule, spec -> spec.onException(UnrulyException.class,
b -> b.execute(action((Exception ex) -> log.warn("step failed", ex)))))
// 2. Flow-level global — fallback for any step without a matching step handler
.onException(Exception.class, b -> b.bind(handled -> true))
  • The step handler is checked first, then the flow-level (global) handler; if neither matches, the exception propagates out of run().
  • Async steps have their own onException on AsyncRunSpec — see below. A failed async step that a handler catches, its own or the flow-level one, completes its future with null, and the flow carries on.
  • To abort from a handler instead of continuing, rethrow from inside its body; a failure of the handler body propagates out of run(). The finalizer runs either way.
  • The flow-level handler covers the flow’s steps only. A failing returning extractor propagates.
  • context() is forbidden inside handler bodies — it throws at build time.

asyncRun(...) launches a Rule, RuleSet, RuleFlow, or registry lookup on the context’s executor service. Bind the resulting CompletableFuture with as(...) and block on it later. (new in 2.2.0) By default the step runs on a fork of the flow’s context, taken when the step executes, so a RuleSet or nested flow — which pushes scopes of its own — is safe to launch asynchronously, even several at once:

.asyncRun(pricingRuleSet, spec -> spec
.as("pricingFuture")) // INHERITED (default) — runs on a fork of the flow's context
.asyncRun(taxRuleSet, spec -> spec
.as("taxFuture")
.withImmutableBindings()) // IMMUTABLE — snapshot, task can't write any binding
.asyncRun(inventoryRule, spec -> spec
.as("inventoryFuture")
.thenRun("result", b -> b // non-blocking continuation on completion
.execute(action(() -> log.info("inventory done"))))
.onException(Exception.class, // fires even if never awaited
b -> b.bind(inventoryFailed -> true)))
.awaitAll("pricingFuture", "inventoryFuture") // default timeout 30s
// await does NOT unwrap — the binding stays a CompletableFuture
.apply(function((CompletableFuture<BigDecimal> pricingFuture) ->
pricingFuture.getNow(null)), spec -> spec.as("price"))
Context Mode Behavior
INHERITED (default) (new in 2.2.0) The task, its thenRun continuation and its onException handler run on a RuleContext.fork() taken when the step executes. The fork shares every scope the flow has at that moment, by reference — a value set on those bindings by either side is seen by both — while the bindings and scopes the task adds stay private to it, and the scopes the flow pushes or pops afterwards do not affect it
IMMUTABLE — withImmutableBindings() The task reads an immutable snapshot; it cannot mutate the caller’s bindings
CUSTOM — withContext(ctx) The task runs against a completely independent, user-supplied RuleContext

Under INHERITED the task’s result reaches the flow in one of two ways: through the future (await, then the bound CompletableFuture), or through a binding the flow declared before the step and the task sets with setValue. Completion of the future orders the task’s writes before the awaiting thread’s reads. A binding the task creates is never seen by the flow.

context(...) customizes the RuleContext the flow builds when invoked without one. It must be the first pipeline step and may only be called once. When the caller supplies a context via run(ruleContext), the context(...) settings layer on top of it:

RuleFlow<RuleContext> flow = RuleFlow.builder()
.name("customContextFlow")
.context(ctx -> ctx.matchUsing(MatchByTypeMatchingStrategy.class))
.run(myRule)
.build();

(new in 2.1.0) The context(configurator, label) overload names the configurator (an XML bean name, for example). RuleFlowDefinition.getContextLabel() reports the label; without one, the configurator’s class name is the default, and null when no configurator was set.

Flows compose: run(otherFlow) nests one flow inside another, and RuleFlows are registrable in the RuleRegistry alongside Rules and RuleSets:

RuleRegistry registry = RuleRegistry.builder().build();
registry.register(checkoutFlow);
RuleFlow<?> flow = registry.getRuleFlow("CheckoutFlow"); // new in 2.0
List<RuleFlow<?>> flows = registry.getRuleFlows();

RuleFlow execution is fully traced — RuleFlowListener events fire through the Tracer for flow and command start, completion, and errors. See Rule Tracing & Debugging.

Two extension points cover cases the built-in steps don’t:

// 1. Inject a pre-built custom command as a leaf step
.command(new MetricsCommand("checkout"))
// 2. Custom container commands (retry, parallel, circuit-breaker, ...)
public abstract class MyBaseBuilder<SELF extends MyBaseBuilder<SELF>>
extends RuleFlowBuilderTemplate<SELF> {
public SELF retry(int maxAttempts, Consumer<SELF> body) {
return runContainer(new RetryCommand(maxAttempts), body);
}
}

Every RuleFlowCommand now describes itself: getInfo() returns a CommandInfo — Run, Apply, Execute, AsyncRun, Await, Bind, When, ForEach, Scope, Exit or Custom — and the flow’s RuleFlowDefinition carries the full command tree via getCommands(). You can read everything a flow is made of off the built object without running it. See Introspection & Metadata for the details.

Mistake Fix
context() after another step, or called twice It must be the first pipeline step, once only
Expecting await("f") to replace the binding with the value The binding stays a CompletableFuture — read it via getNow(null) / join()
Commands after a top-level exit() build() throws — the commands are unreachable
Looking for endWhen() / endScope() Container bodies are Consumer<builder> lambdas — the lambda is the scope
Calling as() / with() on the builder itself Step configuration only exists inside the spec -> consumer
returning(...) without a type witness Use .<String>returning(...) so build() infers RuleFlow<String>
Expecting a step-level handler to abort the flow A step-level handler is catch-and-continue — rethrow inside its body to abort
Expecting a flow-level handler to end the flow, as it did up to 2.2.0 From 2.3.0 the flow carries on with the next top-level step — end the handler body with exit() to stop
Expecting the rest of a when, forEach or scope to run after the flow-level handler has caught a failure inside it The container is abandoned and the flow resumes after it — put the handler on the step (spec.onException(...)) to carry on inside
Async step’s new bindings not visible to the flow Default mode is INHERITED — the task’s own bindings are private. Declare the output binding before the step and have the task setValue it, or read the future after await

Using Spring? RuleFlows can also be declared entirely in XML — see XML RuleFlows.