Lesson 8: Expressions
Every value of a definition is an expression. This lesson shows each kind, then a workflow that computes a quote total and a priority with expressions only.
The static fields below are expression values to read. Inside a workflow Spec, WorkflowExpr.Binary builds with the warning WF021 (the workflow is compiled when the publisher starts); the workflow below uses the add function, which the generator bundles at build time.
Literals and paths
// Literals.
public static readonly WorkflowExpressionDefinition Text = WorkflowExpr.String("Northwind Traders");
public static readonly WorkflowExpressionDefinition Quantity = WorkflowExpr.Number(12);
public static readonly WorkflowExpressionDefinition Price = WorkflowExpr.Number(19.95m);
public static readonly WorkflowExpressionDefinition Flag = WorkflowExpr.Bool(true);
public static readonly WorkflowExpressionDefinition Nothing = WorkflowExpr.Null();
// Paths: start.* (the start request), state.* (the workflow state), payload.* (the completion
// payload of the task being completed), result.* (the results kept with a result key).
public static readonly WorkflowExpressionDefinition Customer = WorkflowExpr.Path("start.customer");
public static readonly WorkflowExpressionDefinition FirstLineSku = WorkflowExpr.Path("state.lines.0.sku");
Objects and arrays
public static readonly WorkflowExpressionDefinition OrderSummary = WorkflowExpr.Obj(
WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId")),
WorkflowExpr.Prop("tags", WorkflowExpr.Array(WorkflowExpr.String("priority"), WorkflowExpr.String("export"))));
Operators
// Comparison, logical and arithmetic operators.
public static readonly WorkflowExpressionDefinition LargeExportOrder = WorkflowExpr.And(
WorkflowExpr.Gt(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(10000)),
WorkflowExpr.Eq(WorkflowExpr.Path("state.region"), WorkflowExpr.String("export")));
public static readonly WorkflowExpressionDefinition NotCancelled =
WorkflowExpr.Not(WorkflowExpr.Eq(WorkflowExpr.Path("state.status"), WorkflowExpr.String("cancelled")));
public static readonly WorkflowExpressionDefinition WithinBudget =
WorkflowExpr.Lte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Path("state.budget"));
public static readonly WorkflowExpressionDefinition LineTotal = WorkflowExpr.Binary(
"multiply", WorkflowExpr.Path("state.quantity"), WorkflowExpr.Path("state.unitPrice"));
Functions
// Functions of the core catalogue (GET /api/workflow/functions lists the installed ones).
public static readonly WorkflowExpressionDefinition ContactName = WorkflowExpr.Func(
"coalesce", WorkflowExpr.Path("payload.contactName"), WorkflowExpr.Path("state.contactName"), WorkflowExpr.String("unknown"));
public static readonly WorkflowExpressionDefinition Reference = WorkflowExpr.Func(
"concat", WorkflowExpr.String("ORD-"), WorkflowExpr.Func("upper", WorkflowExpr.Path("state.region")));
public static readonly WorkflowExpressionDefinition Priority = WorkflowExpr.Func(
"if",
WorkflowExpr.Gte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(5000)),
WorkflowExpr.String("high"),
WorkflowExpr.String("normal"));
public static readonly WorkflowExpressionDefinition HasComment = WorkflowExpr.Not(
WorkflowExpr.Func("isNullOrWhiteSpace", WorkflowExpr.Path("payload.comment")));
// The add function sums any number of arguments.
public static readonly WorkflowExpressionDefinition Total = WorkflowExpr.Func(
"add", WorkflowExpr.Path("state.netAmount"), WorkflowExpr.Path("state.tax"));
A workflow
/// <summary>Computes a quote total and a priority with expressions only; large quotes need a sign-off.</summary>
public sealed class PriceQuoteWorkflow : IDeclarativeWorkflow<PriceQuoteRequest>
{
public string WorkflowName => "PriceQuote";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Price quote";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["sales"];
public WorkflowSpec<PriceQuoteRequest> Spec { get; } = WorkflowSpec.For<PriceQuoteRequest>()
.InitializeState(
WorkflowExpr.Obj(
WorkflowExpr.Prop("quoteId", WorkflowExpr.Path("start.quoteId")),
WorkflowExpr.Prop("region", WorkflowExpr.Func("upper", WorkflowExpr.Path("start.region"))),
WorkflowExpr.Prop("netAmount", WorkflowExpr.Path("start.netAmount")),
WorkflowExpr.Prop("tax", WorkflowExpr.Path("start.tax"))))
.AddTask(
WorkflowHumanTask.For<PriceQuoteRequest>("Sign off quote", "QuoteSignOff", "sales/quotes")
.WithPayload(
WorkflowExpr.Obj(
WorkflowExpr.Prop("quoteId", WorkflowExpr.Path("state.quoteId")),
WorkflowExpr.Prop("amount", WorkflowExpr.Path("state.amount"))))
.OnComplete(flow => flow.Complete()))
.StartWith(flow => flow
.Set("amount", WorkflowExpr.Func("add", WorkflowExpr.Path("state.netAmount"), WorkflowExpr.Path("state.tax")))
.Set("priority", WorkflowExpr.Func(
"if",
WorkflowExpr.Gte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(5000)),
WorkflowExpr.String("high"),
WorkflowExpr.String("normal")))
.WhenExpression(
"Needs sign-off?",
WorkflowExpr.Eq(WorkflowExpr.Path("state.priority"), WorkflowExpr.String("high")),
high => high.ActivateTask("Sign off quote"),
normal => normal.Complete()))
.Build();
public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}
A function of your own
A host adds functions with a provider that implements two interfaces: IWorkflowFunctionProvider describes the function for the compiler, the validator and GET /api/workflow/functions, and IWorkflowFunctionRuntimeProvider computes it. This one returns the VAT rate of a country:
/// <summary>
/// A function module of your own: <c>vatRate(countryCode)</c> returns the VAT rate of a country as a
/// decimal. The descriptor makes the function known to the compiler, the validator and the function
/// catalog of the HTTP API; <see cref="TryEvaluate"/> computes it at run time.
/// </summary>
public sealed class VatFunctionProvider : IWorkflowFunctionProvider, IWorkflowFunctionRuntimeProvider
{
public const string ModuleName = "contoso.functions.tax";
public const string ModuleVersion = "1.0.0";
private static readonly IReadOnlyDictionary<string, decimal> Rates = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
["DE"] = 0.19m,
["FR"] = 0.20m,
["NL"] = 0.21m,
};
public IReadOnlyCollection<WorkflowFunctionDescriptor> GetFunctions() =>
[
new WorkflowFunctionDescriptor
{
FunctionName = "vatRate",
ModuleName = ModuleName,
ModuleVersion = ModuleVersion,
Summary = "Returns the VAT rate of a country; 0 for a country without a rate.",
Arguments =
[
new WorkflowFunctionArgumentDescriptor
{
Name = "countryCode",
Type = "string",
Required = true,
Description = "The ISO 3166-1 alpha-2 country code.",
},
],
Return = new WorkflowFunctionReturnDescriptor { Type = "number", Description = "The rate, for example 0.19." },
Examples = [new WorkflowFunctionExample { Expression = "vatRate(state.country)" }],
},
];
public bool TryEvaluate(
string functionName,
IReadOnlyCollection<object?> arguments,
WorkflowCanonicalEvaluationContext context,
out object? result)
{
if (!string.Equals(functionName, "vatRate", StringComparison.Ordinal))
{
// Not this module's function: the engine asks the next provider.
result = null;
return false;
}
var countryCode = Convert.ToString(arguments.FirstOrDefault(), CultureInfo.InvariantCulture) ?? string.Empty;
result = Rates.TryGetValue(countryCode, out var rate) ? rate : 0m;
return true;
}
}
Install the provider and the module its descriptor names in every host that runs or validates a workflow that uses the function:
/// <summary>Installs the function module in the host: the provider and the module it declares.</summary>
public static IServiceCollection AddVatFunctions(this IServiceCollection services)
{
services.AddWorkflowFunctionProvider<VatFunctionProvider>();
services.AddWorkflowModule(VatFunctionProvider.ModuleName, VatFunctionProvider.ModuleVersion);
return services;
}
A workflow calls the function by its name, like a core function:
// A custom function is called like a core function, by its name.
.StartWith(flow => flow
.Set("vatRate", WorkflowExpr.Func("vatRate", WorkflowExpr.Path("state.country")))
.Complete())
An invoice for DE completes with state.vatRate 0.19; a country without a rate gets 0. The function runs on both runtime providers.
Cases:
- Lookups the expressions cannot do. A rate table, a holiday calendar, a currency rounding rule.
- A rule your organisation owns. One provider, shared by every workflow and every host that loads it.
Pitfalls:
- A host without the function. Validation and import refuse a definition that calls an unknown function with
WFVAL064. Install the provider in every host that validates, imports or runs the workflow. - Calls and side effects. A function runs inside expression evaluation and may run again when a step is retried. Keep it deterministic and free of side effects: read a fixed table, compute, return. Call services with a
Callstep instead. - Names. A name that a core function or another module already uses, in any letter case or as an alias, is refused: the host stops when it starts, with “Workflow function ‘
’ is registered more than once by modules ‘’ and ‘’.” Choose names that are unique to your module.
Concepts
- Five path roots:
start,state,payload,result, andbusinessReference(thekeyandpartsof the instance’s business reference). - A step sees the state as the earlier steps left it:
Set("priority", ...)readsstate.amount, set one step earlier. GET /api/workflow/functionslists the functions a host has, with their arguments and examples.
The complete code
The lesson’s complete code. It uses the namespace of the tutorials; put the classes in a namespace of yours.
ExpressionExamples.cs:
using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;
namespace Examples.Workflow.Tutorials.Expressions;
/// <summary>Expressions of the canonical form, built with WorkflowExpr.</summary>
public static class ExpressionExamples
{
// Literals.
public static readonly WorkflowExpressionDefinition Text = WorkflowExpr.String("Northwind Traders");
public static readonly WorkflowExpressionDefinition Quantity = WorkflowExpr.Number(12);
public static readonly WorkflowExpressionDefinition Price = WorkflowExpr.Number(19.95m);
public static readonly WorkflowExpressionDefinition Flag = WorkflowExpr.Bool(true);
public static readonly WorkflowExpressionDefinition Nothing = WorkflowExpr.Null();
// Paths: start.* (the start request), state.* (the workflow state), payload.* (the completion
// payload of the task being completed), result.* (the results kept with a result key).
public static readonly WorkflowExpressionDefinition Customer = WorkflowExpr.Path("start.customer");
public static readonly WorkflowExpressionDefinition FirstLineSku = WorkflowExpr.Path("state.lines.0.sku");
public static readonly WorkflowExpressionDefinition OrderSummary = WorkflowExpr.Obj(
WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId")),
WorkflowExpr.Prop("tags", WorkflowExpr.Array(WorkflowExpr.String("priority"), WorkflowExpr.String("export"))));
// Comparison, logical and arithmetic operators.
public static readonly WorkflowExpressionDefinition LargeExportOrder = WorkflowExpr.And(
WorkflowExpr.Gt(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(10000)),
WorkflowExpr.Eq(WorkflowExpr.Path("state.region"), WorkflowExpr.String("export")));
public static readonly WorkflowExpressionDefinition NotCancelled =
WorkflowExpr.Not(WorkflowExpr.Eq(WorkflowExpr.Path("state.status"), WorkflowExpr.String("cancelled")));
public static readonly WorkflowExpressionDefinition WithinBudget =
WorkflowExpr.Lte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Path("state.budget"));
public static readonly WorkflowExpressionDefinition LineTotal = WorkflowExpr.Binary(
"multiply", WorkflowExpr.Path("state.quantity"), WorkflowExpr.Path("state.unitPrice"));
// Functions of the core catalogue (GET /api/workflow/functions lists the installed ones).
public static readonly WorkflowExpressionDefinition ContactName = WorkflowExpr.Func(
"coalesce", WorkflowExpr.Path("payload.contactName"), WorkflowExpr.Path("state.contactName"), WorkflowExpr.String("unknown"));
public static readonly WorkflowExpressionDefinition Reference = WorkflowExpr.Func(
"concat", WorkflowExpr.String("ORD-"), WorkflowExpr.Func("upper", WorkflowExpr.Path("state.region")));
public static readonly WorkflowExpressionDefinition Priority = WorkflowExpr.Func(
"if",
WorkflowExpr.Gte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(5000)),
WorkflowExpr.String("high"),
WorkflowExpr.String("normal"));
public static readonly WorkflowExpressionDefinition HasComment = WorkflowExpr.Not(
WorkflowExpr.Func("isNullOrWhiteSpace", WorkflowExpr.Path("payload.comment")));
// The add function sums any number of arguments.
public static readonly WorkflowExpressionDefinition Total = WorkflowExpr.Func(
"add", WorkflowExpr.Path("state.netAmount"), WorkflowExpr.Path("state.tax"));
}
public sealed class PriceQuoteRequest
{
[WorkflowBusinessId]
public string QuoteId { get; set; } = string.Empty;
public string Region { get; set; } = string.Empty;
public decimal NetAmount { get; set; }
public decimal Tax { get; set; }
}
/// <summary>Computes a quote total and a priority with expressions only; large quotes need a sign-off.</summary>
public sealed class PriceQuoteWorkflow : IDeclarativeWorkflow<PriceQuoteRequest>
{
public string WorkflowName => "PriceQuote";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Price quote";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["sales"];
public WorkflowSpec<PriceQuoteRequest> Spec { get; } = WorkflowSpec.For<PriceQuoteRequest>()
.InitializeState(
WorkflowExpr.Obj(
WorkflowExpr.Prop("quoteId", WorkflowExpr.Path("start.quoteId")),
WorkflowExpr.Prop("region", WorkflowExpr.Func("upper", WorkflowExpr.Path("start.region"))),
WorkflowExpr.Prop("netAmount", WorkflowExpr.Path("start.netAmount")),
WorkflowExpr.Prop("tax", WorkflowExpr.Path("start.tax"))))
.AddTask(
WorkflowHumanTask.For<PriceQuoteRequest>("Sign off quote", "QuoteSignOff", "sales/quotes")
.WithPayload(
WorkflowExpr.Obj(
WorkflowExpr.Prop("quoteId", WorkflowExpr.Path("state.quoteId")),
WorkflowExpr.Prop("amount", WorkflowExpr.Path("state.amount"))))
.OnComplete(flow => flow.Complete()))
.StartWith(flow => flow
.Set("amount", WorkflowExpr.Func("add", WorkflowExpr.Path("state.netAmount"), WorkflowExpr.Path("state.tax")))
.Set("priority", WorkflowExpr.Func(
"if",
WorkflowExpr.Gte(WorkflowExpr.Path("state.amount"), WorkflowExpr.Number(5000)),
WorkflowExpr.String("high"),
WorkflowExpr.String("normal")))
.WhenExpression(
"Needs sign-off?",
WorkflowExpr.Eq(WorkflowExpr.Path("state.priority"), WorkflowExpr.String("high")),
high => high.ActivateTask("Sign off quote"),
normal => normal.Complete()))
.Build();
public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}
CustomFunctions.cs:
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;
namespace Examples.Workflow.Tutorials.Expressions;
/// <summary>
/// A function module of your own: <c>vatRate(countryCode)</c> returns the VAT rate of a country as a
/// decimal. The descriptor makes the function known to the compiler, the validator and the function
/// catalog of the HTTP API; <see cref="TryEvaluate"/> computes it at run time.
/// </summary>
public sealed class VatFunctionProvider : IWorkflowFunctionProvider, IWorkflowFunctionRuntimeProvider
{
public const string ModuleName = "contoso.functions.tax";
public const string ModuleVersion = "1.0.0";
private static readonly IReadOnlyDictionary<string, decimal> Rates = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
["DE"] = 0.19m,
["FR"] = 0.20m,
["NL"] = 0.21m,
};
public IReadOnlyCollection<WorkflowFunctionDescriptor> GetFunctions() =>
[
new WorkflowFunctionDescriptor
{
FunctionName = "vatRate",
ModuleName = ModuleName,
ModuleVersion = ModuleVersion,
Summary = "Returns the VAT rate of a country; 0 for a country without a rate.",
Arguments =
[
new WorkflowFunctionArgumentDescriptor
{
Name = "countryCode",
Type = "string",
Required = true,
Description = "The ISO 3166-1 alpha-2 country code.",
},
],
Return = new WorkflowFunctionReturnDescriptor { Type = "number", Description = "The rate, for example 0.19." },
Examples = [new WorkflowFunctionExample { Expression = "vatRate(state.country)" }],
},
];
public bool TryEvaluate(
string functionName,
IReadOnlyCollection<object?> arguments,
WorkflowCanonicalEvaluationContext context,
out object? result)
{
if (!string.Equals(functionName, "vatRate", StringComparison.Ordinal))
{
// Not this module's function: the engine asks the next provider.
result = null;
return false;
}
var countryCode = Convert.ToString(arguments.FirstOrDefault(), CultureInfo.InvariantCulture) ?? string.Empty;
result = Rates.TryGetValue(countryCode, out var rate) ? rate : 0m;
return true;
}
}
public static class CustomFunctionRegistrations
{
/// <summary>Installs the function module in the host: the provider and the module it declares.</summary>
public static IServiceCollection AddVatFunctions(this IServiceCollection services)
{
services.AddWorkflowFunctionProvider<VatFunctionProvider>();
services.AddWorkflowModule(VatFunctionProvider.ModuleName, VatFunctionProvider.ModuleVersion);
return services;
}
}
public sealed class InvoiceTaxRequest
{
[WorkflowBusinessId]
public string InvoiceId { get; set; } = string.Empty;
public string Country { get; set; } = string.Empty;
}
/// <summary>Reads the VAT rate of the invoice's country with the custom function.</summary>
public sealed class InvoiceTaxWorkflow : IDeclarativeWorkflow<InvoiceTaxRequest>
{
public string WorkflowName => "InvoiceTax";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Invoice tax";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["accounting"];
public WorkflowSpec<InvoiceTaxRequest> Spec { get; } = WorkflowSpec.For<InvoiceTaxRequest>()
.InitializeState(
WorkflowExpr.Obj(
WorkflowExpr.Prop("invoiceId", WorkflowExpr.Path("start.invoiceId")),
WorkflowExpr.Prop("country", WorkflowExpr.Path("start.country"))))
// A custom function is called like a core function, by its name.
.StartWith(flow => flow
.Set("vatRate", WorkflowExpr.Func("vatRate", WorkflowExpr.Path("state.country")))
.Complete())
.Build();
public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}
The canonical form
The C# compiles to a canonical JSON definition, the document the engine validates, stores and renders. Write it to a file with the export helper of lesson 9:
CanonicalExport.WriteCanonicalJson(new PriceQuoteWorkflow(), "price-quote.definition.json");CanonicalExport.WriteCanonicalJson(new InvoiceTaxWorkflow(), "invoice-tax.definition.json");
Next: Lesson 9: Testing.
