Canonical definitions
Every workflow has a canonical form: a JSON document with the schema identifier stellaops.workflow.definition/v1. The engine compiles each C# workflow to this form; it validates, stores, hashes, renders and exports the canonical form; and you can write a definition directly in it. This page describes the document, the analyzer that keeps C# workflows compilable to it, and the tools that move between the two forms.
When to use the JSON form
| Use the C# builder when | Use canonical JSON when |
|---|---|
| The workflows ship with your application | Definitions are data: reviewed, versioned and deployed separately from code |
| You want compile-time checks and refactoring | A design tool or another service produces the definitions |
| You validate, render, review or store definitions without running them |
The engine runs workflows registered in code. A JSON definition is stored with an import and governed with an activation (Governed activation and publishing); it is not run.
The document
The tutorial Hello world compiles to this definition:
{
"schemaVersion": "stellaops.workflow.definition/v1",
"workflowName": "AcknowledgeDocument",
"workflowVersion": "1.0.0",
"displayName": "Acknowledge a document",
"startRequest": {
"contractName": "Examples.Workflow.Tutorials.HelloWorld.AcknowledgeDocumentRequest",
"schema": {
"type": "object",
"properties": {
"documentId": {
"type": "string"
},
"recipient": {
"type": "string"
}
}
},
"allowAdditionalProperties": true
},
"workflowRoles": [
"staff"
],
"businessReference": {
"keyExpression": {
"$type": "path",
"path": "start.documentId"
},
"parts": []
},
"start": {
"initializeStateExpression": {
"$type": "object",
"properties": [
{
"name": "documentId",
"expression": {
"$type": "path",
"path": "start.documentId"
}
},
{
"name": "recipient",
"expression": {
"$type": "path",
"path": "start.recipient"
}
}
]
},
"initialSequence": {
"steps": [
{
"$type": "activate-task",
"taskName": "Acknowledge document"
}
]
}
},
"tasks": [
{
"taskName": "Acknowledge document",
"taskType": "DocumentAcknowledgement",
"routeExpression": {
"$type": "string",
"value": "documents/acknowledge"
},
"payloadExpression": {
"$type": "object",
"properties": [
{
"name": "documentId",
"expression": {
"$type": "path",
"path": "state.documentId"
}
}
]
},
"taskRoles": [],
"onComplete": {
"steps": [
{
"$type": "complete"
}
]
}
}
],
"requiredModules": [
{
"moduleName": "workflow.dsl.core",
"versionExpression": ">=1.0.0",
"optional": false
}
],
"requiredCapabilities": []
}
| Property | Content |
|---|---|
schemaVersion | Always stellaops.workflow.definition/v1 |
workflowName, workflowVersion, displayName, workflowRoles | The identity and the roles |
startRequest | The start request contract: its type name and a JSON Schema of its properties |
businessReference | How the business reference is built from the start request, when the start request has a business key |
start | initializeStateExpression and initialSequence.steps |
tasks | Each human task: taskName, taskType, routeExpression, taskRoles, payloadExpression, timeoutSeconds, singleOpenSlot, onComplete, onTimeout |
requiredModules | The modules the definition needs (for example transport.http for an http call); the validator checks that the host has them |
Steps, expressions and addresses are objects with a $type discriminator:
| Group | $type values |
|---|---|
| Steps | set-state, assign-business-reference, activate-task, call-transport, external-activity, decision, repeat, map, fork, terminate-fork, timer, external-signal, sub-workflow, continue-with-workflow, complete |
| Expressions | null, string, number, boolean, path, object, array, function, group, binary, unary |
| Addresses | endpoint, http, graphql, rabbit |
GET /api/workflow/canonical/schema returns the complete JSON Schema of the document, generated by the engine you run.
Writing a definition in JSON
A call-transport step’s timeoutSeconds is the timeoutSeconds argument of the C# call, and a rabbit address is a C# RabbitAddress (Calling services).
Validate a document before you import it. inventory-restock.definition.json is the workflow of lesson 2 of the tutorials, written to a file as “Compiling C# to JSON” below shows:
curl -s -X POST http://localhost:5090/api/workflow/canonical/validate \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"canonicalDefinitionJson\": $(jq -Rs . < inventory-restock.definition.json)}"
The response has isValid, the schema, semantic and module issues, and the modules the host has installed. A semantic issue names the step and the rule (for example an activate-task step for a task that is not declared).
Formats
GET /api/workflow/supported-formats lists the source formats of the multi-format import and export:
| Format id | Content |
|---|---|
canonical-json | The canonical JSON document |
canonical-yaml | The same document in YAML |
canonical-bundle | A ZIP bundle with the definition |
POST /api/workflow/definitions/import-multi takes formatId and the content in base64; export-multi returns a definition in a format (Human tasks and the HTTP API).
Compiling C# to JSON
WorkflowCanonicalDefinitionCompiler.Compile (in StellaOps.Workflow.Abstractions) compiles a workflow object; WorkflowCanonicalJsonSerializer writes and reads the JSON. A unit test can compile and validate a definition without a database:
[Test]
public void TheDefinitionCompilesToAValidCanonicalDefinition()
{
var compilation = WorkflowCanonicalDefinitionCompiler.Compile(new DocumentReviewWorkflow());
Assert.That(compilation.Succeeded, Is.True, string.Join("; ", compilation.Diagnostics.Select(d => d.Message)));
// The engine's validator: the schema, the expressions, and the modules the definition needs.
using var services = new ServiceCollection()
.AddLogging()
.AddWorkflowEngineCoreServices(new ConfigurationBuilder().Build())
.BuildServiceProvider();
using var scope = services.CreateScope();
var validation = scope.ServiceProvider.GetRequiredService<WorkflowCanonicalDefinitionService>()
.Validate(new WorkflowCanonicalValidateRequest
{
CanonicalDefinitionJson = WorkflowCanonicalJsonSerializer.Serialize(compilation.Definition!),
});
var issues = validation.SchemaIssues.Concat(validation.SemanticIssues).Concat(validation.ModuleIssues);
Assert.That(validation.IsValid, Is.True, string.Join("; ", issues.Select(issue => $"{issue.Path}: {issue.Message}")));
}
At build time, the workflow analyzer package also contains a source generator that writes the canonical JSON of each workflow of a project into the assembly; the publisher reads it from there. A workflow the generator cannot evaluate (WF021) is listed for runtime compilation instead, and the publisher compiles it when it starts.
There is no tool that turns a canonical definition back into C# source; write the C# by hand when you move a definition from JSON to code, then compare the compiled JSON with the original.
To write the JSON to a file, for a review or an import:
/// <summary>
/// Writes the canonical JSON of a workflow to a file: the document to review, to validate, or to import
/// into a workflow host.
/// </summary>
public static void WriteCanonicalJson<TStartRequest>(IDeclarativeWorkflow<TStartRequest> workflow, string path)
where TStartRequest : class
{
var compilation = WorkflowCanonicalDefinitionCompiler.Compile(workflow);
if (!compilation.Succeeded)
{
throw new InvalidOperationException(
string.Join("; ", compilation.Diagnostics.Select(diagnostic => $"{diagnostic.Code}: {diagnostic.Message}")));
}
File.WriteAllText(path, WorkflowCanonicalJsonSerializer.Serialize(compilation.Definition!));
}
The analyzer
A project that references StellaOps.Workflow.Abstractions gets the analyzer. It checks the Spec of every workflow class at compile time; its errors fail the build, and WF021 is a warning:
| Rule | Rejects | Write instead |
|---|---|---|
| WF001 | if, switch, loops, try, throw in a Spec | WhenExpression, Repeat, failure branches |
| WF002 | async and await | Steps; the engine waits durably |
| WF003 | Calls into assemblies other than the Workflow packages | WorkflowExpr functions, or a helper in your own project |
| WF004 | new on types of other assemblies | WorkflowExpr.Obj and WorkflowExpr.Array |
| WF005 | ?:, ??, ?. | WorkflowExpr.Func("if", ...), coalesce |
| WF006 | Reads of fields and properties that hold build-time values | WorkflowExpr.Path for runtime values; literals or const |
| WF010 | A helper in another project of yours that breaks a rule above | Fix the helper; the error points at both places |
| WF020 | A class that implements IDeclarativeWorkflow<T> without a Spec property | A Spec built with WorkflowSpec.For<T>() |
| WF021 (warning) | A construct the source generator cannot evaluate at build time; the workflow builds and runs, and the publisher compiles it when it starts, except a delegate form (Run, context => ...), which has no canonical form: the publisher and a Stella.Engine host reject it when they start | Nothing for a workflow registered in code, except a delegate form: use the expression form. Literals in place keep a workflow in the bundle (Defining workflows) |
The rules, their exact scope and the trusted-assembly settings are in the analyzer reference.
Content hash and versions
The engine hashes the canonical form of a definition. The definition store keys a version by name and version and keeps its hash: importing the same content again is a no-op, and different content under an existing version is refused (WORKFLOW_DEFINITION_VERSION_HASH_CONFLICT). Change the version whenever the content changes.
Pitfalls
- Editing a stored version. A stored version never changes. Import the change under a new version and activate it.
- Expecting an import to run. An imported definition is stored; the engine runs the workflows registered in code (Governed activation and publishing).
- A module the host lacks. A definition with an
httpcall needs the HTTP transport in the host. The validator reports it as a module issue. - Case. JSON property names are camel case, and
$typevalues are lower case with hyphens.
Related
- Defining workflows
- Analyzer reference
- Tutorials: every lesson has its complete C# code and the export of its canonical JSON.
- .NET API reference:
WorkflowCanonicalDefinition,WorkflowCanonicalDefinitionCompiler,WorkflowCanonicalDefinitionValidatorandWorkflowCanonicalJsonSerializer
