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 whenUse canonical JSON when
The workflows ship with your applicationDefinitions are data: reviewed, versioned and deployed separately from code
You want compile-time checks and refactoringA 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": []
}
PropertyContent
schemaVersionAlways stellaops.workflow.definition/v1
workflowName, workflowVersion, displayName, workflowRolesThe identity and the roles
startRequestThe start request contract: its type name and a JSON Schema of its properties
businessReferenceHow the business reference is built from the start request, when the start request has a business key
startinitializeStateExpression and initialSequence.steps
tasksEach human task: taskName, taskType, routeExpression, taskRoles, payloadExpression, timeoutSeconds, singleOpenSlot, onComplete, onTimeout
requiredModulesThe 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
Stepsset-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
Expressionsnull, string, number, boolean, path, object, array, function, group, binary, unary
Addressesendpoint, 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 idContent
canonical-jsonThe canonical JSON document
canonical-yamlThe same document in YAML
canonical-bundleA 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:

RuleRejectsWrite instead
WF001if, switch, loops, try, throw in a SpecWhenExpression, Repeat, failure branches
WF002async and awaitSteps; the engine waits durably
WF003Calls into assemblies other than the Workflow packagesWorkflowExpr functions, or a helper in your own project
WF004new on types of other assembliesWorkflowExpr.Obj and WorkflowExpr.Array
WF005?:, ??, ?.WorkflowExpr.Func("if", ...), coalesce
WF006Reads of fields and properties that hold build-time valuesWorkflowExpr.Path for runtime values; literals or const
WF010A helper in another project of yours that breaks a rule aboveFix the helper; the error points at both places
WF020A class that implements IDeclarativeWorkflow<T> without a Spec propertyA 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 startNothing 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