Lesson 6: Advanced patterns
Supplier onboarding runs three checks in parallel and retries a registration with a pause between attempts. Two more definitions wait for a signal from outside and fan out over a batch. Every workflow of this lesson runs on Stella.Engine, the default runtime provider (Hosting).
Parallel branches
// Three branches run concurrently; the flow continues when all three have finished.
.Fork(
"Run onboarding checks",
credit => credit.Call("Check credit", new EndpointAddress("risk", "/credit-checks"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))),
sanctions => sanctions.Call("Screen supplier", new EndpointAddress("risk", "/screenings"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))),
tax => tax.Call("Validate tax number", new HttpAddress("tax-registry", "/validations"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))))
A loop with a timer
// Up to three attempts while the registration is not confirmed, one minute apart.
.Repeat(
"Register supplier",
3,
"registrationAttempt",
WorkflowExpr.Ne(WorkflowExpr.Path("state.registration"), WorkflowExpr.String("confirmed")),
attempt => attempt
.Call<object>(
"Submit registration",
new EndpointAddress("erp", "/suppliers"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId"))),
resultKey: "registration")
.Set("registration", WorkflowExpr.Path("result.registration.status"))
.Wait("Pause before the next attempt", WorkflowExpr.String("00:01:00")))
Waiting for an external signal
SupplierDocumentsWorkflow waits until a client reports that the supplier’s documents are uploaded. A client resumes the instance with POST /api/workflow/signals/raise (Human tasks and the HTTP API):
// The instance waits until a client raises the signal "documents-uploaded" for it; the signal's
// payload is kept under "result.documents".
.WaitForSignal("Wait for documents", "documents-uploaded", "documents")
.Set("documentCount", WorkflowExpr.Path("result.documents.count"))
Fanning out over a collection
PriceUpdateWorkflow sets the price of every line of a batch with a Map step, four lines at a time. A map needs the durable services (Durable execution):
// One body per line, at most four at a time; each line is under "state.line" while its body runs,
// and the results are collected under "result.updates".
.Map(
"Update prices",
WorkflowExpr.Path("state.lines"),
WorkflowExpr.Path("state.line.sku"),
WorkflowExpr.Path("result.update"),
"line",
4,
500,
65536,
body => body.Call<object>(
"Set price",
new EndpointAddress("pricing", "/prices"),
WorkflowExpr.Obj(
WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.line.sku")),
WorkflowExpr.Prop("price", WorkflowExpr.Path("state.line.price"))),
resultKey: "update"),
resultKey: "updates")
WaitForSignal and Map build with the warning WF021: the workflow is left out of the build-time bundle, and the publisher compiles it when it starts (analyzer rules).
Concepts
Forkwaits for all branches;TerminateForkin a branch ends the fork early.Repeatneeds a maximum; the condition decides whether another iteration runs.Waittakes a number of milliseconds (a number or a string of digits) or a time-span string such as"00:01:00"; the signal pump resumes the instance.WaitForSignalkeeps the signal’s payload underresult.<resultKey>;Mapcollects the item results under its result key.
The complete code
The lesson’s complete code. It uses the namespace of the tutorials; put the classes in a namespace of yours.
SupplierOnboardingWorkflow.cs:
using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;
namespace Examples.Workflow.Tutorials.AdvancedPatterns;
public sealed class SupplierOnboardingRequest
{
[WorkflowBusinessId]
public string SupplierId { get; set; } = string.Empty;
public string Country { get; set; } = string.Empty;
}
/// <summary>
/// Onboards a supplier: three checks run in parallel, then the registration call is retried up to
/// three times with a pause between attempts.
/// </summary>
public sealed class SupplierOnboardingWorkflow : IDeclarativeWorkflow<SupplierOnboardingRequest>
{
public string WorkflowName => "SupplierOnboarding";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Supplier onboarding";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["procurement"];
public WorkflowSpec<SupplierOnboardingRequest> Spec { get; } = WorkflowSpec.For<SupplierOnboardingRequest>()
.InitializeState(
WorkflowExpr.Obj(
WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("start.supplierId")),
WorkflowExpr.Prop("country", WorkflowExpr.Path("start.country")),
WorkflowExpr.Prop("registration", WorkflowExpr.String("pending"))))
.StartWith(flow => flow
// Three branches run concurrently; the flow continues when all three have finished.
.Fork(
"Run onboarding checks",
credit => credit.Call("Check credit", new EndpointAddress("risk", "/credit-checks"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))),
sanctions => sanctions.Call("Screen supplier", new EndpointAddress("risk", "/screenings"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))),
tax => tax.Call("Validate tax number", new HttpAddress("tax-registry", "/validations"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId")))))
// Up to three attempts while the registration is not confirmed, one minute apart.
.Repeat(
"Register supplier",
3,
"registrationAttempt",
WorkflowExpr.Ne(WorkflowExpr.Path("state.registration"), WorkflowExpr.String("confirmed")),
attempt => attempt
.Call<object>(
"Submit registration",
new EndpointAddress("erp", "/suppliers"),
WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("state.supplierId"))),
resultKey: "registration")
.Set("registration", WorkflowExpr.Path("result.registration.status"))
.Wait("Pause before the next attempt", WorkflowExpr.String("00:01:00")))
.Complete())
.Build();
public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}
SignalAndMapWorkflows.cs:
using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;
namespace Examples.Workflow.Tutorials.AdvancedPatterns;
public sealed class SupplierDocumentsRequest
{
[WorkflowBusinessId]
public string SupplierId { get; set; } = string.Empty;
}
/// <summary>Waits until a client reports that the supplier's documents are uploaded.</summary>
public sealed class SupplierDocumentsWorkflow : IDeclarativeWorkflow<SupplierDocumentsRequest>
{
public string WorkflowName => "SupplierDocuments";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Supplier documents";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["procurement"];
public WorkflowSpec<SupplierDocumentsRequest> Spec { get; } = WorkflowSpec.For<SupplierDocumentsRequest>()
.InitializeState(WorkflowExpr.Obj(WorkflowExpr.Prop("supplierId", WorkflowExpr.Path("start.supplierId"))))
.StartWith(flow => flow
// The instance waits until a client raises the signal "documents-uploaded" for it; the signal's
// payload is kept under "result.documents".
.WaitForSignal("Wait for documents", "documents-uploaded", "documents")
.Set("documentCount", WorkflowExpr.Path("result.documents.count"))
.Complete())
.Build();
public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}
public sealed class PriceUpdateRequest
{
[WorkflowBusinessId]
public string BatchId { get; set; } = string.Empty;
public IReadOnlyCollection<PriceLine> Lines { get; set; } = [];
}
public sealed class PriceLine
{
public string Sku { get; set; } = string.Empty;
public decimal Price { get; set; }
}
/// <summary>Sets the price of every line of a batch, four lines at a time.</summary>
public sealed class PriceUpdateWorkflow : IDeclarativeWorkflow<PriceUpdateRequest>
{
public string WorkflowName => "PriceUpdate";
public string WorkflowVersion => "1.0.0";
public string DisplayName => "Price update";
public IReadOnlyCollection<string> WorkflowRoles { get; } = ["pricing"];
public WorkflowSpec<PriceUpdateRequest> Spec { get; } = WorkflowSpec.For<PriceUpdateRequest>()
.InitializeState(
WorkflowExpr.Obj(
WorkflowExpr.Prop("batchId", WorkflowExpr.Path("start.batchId")),
WorkflowExpr.Prop("lines", WorkflowExpr.Path("start.lines"))))
.StartWith(flow => flow
// One body per line, at most four at a time; each line is under "state.line" while its body runs,
// and the results are collected under "result.updates".
.Map(
"Update prices",
WorkflowExpr.Path("state.lines"),
WorkflowExpr.Path("state.line.sku"),
WorkflowExpr.Path("result.update"),
"line",
4,
500,
65536,
body => body.Call<object>(
"Set price",
new EndpointAddress("pricing", "/prices"),
WorkflowExpr.Obj(
WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.line.sku")),
WorkflowExpr.Prop("price", WorkflowExpr.Path("state.line.price"))),
resultKey: "update"),
resultKey: "updates")
.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 SupplierOnboardingWorkflow(), "supplier-onboarding.definition.json");CanonicalExport.WriteCanonicalJson(new SupplierDocumentsWorkflow(), "supplier-documents.definition.json");CanonicalExport.WriteCanonicalJson(new PriceUpdateWorkflow(), "price-update.definition.json");
Next: Lesson 7: Shared helpers.
