Hosting the engine

The engine runs inside your host. This page describes the registrations of an ASP.NET Core host, the authentication and the three authorization policies, the actor of a task action, health and readiness, and the choices that a production host makes. Getting started builds a complete host step by step.

The composition

// The engine and its PostgreSQL store. The store reads its connection string from
// STELLAOPS_POSTGRES_WORKFLOW_CONNECTION and creates the `workflow` schema at start.
builder.Services.AddWorkflowEngineCoreServices(builder.Configuration);
builder.Services.AddWorkflowPostgresDataStore(builder.Configuration);

// The signal pump, the retention job and the licence monitor, with its `licence` health entry.
builder.Services.AddWorkflowEngineHostedServices();

// Fails at start when WorkflowBackend:Provider or WorkflowSignalDriver:Provider names a backend
// or a signal driver that no registered library provides.
builder.Services.ValidateWorkflowProviderRegistrations(builder.Configuration);
RegistrationPackageRegisters
AddWorkflowEngineCoreServices(configuration)StellaOps.Workflow.EngineThe runtime, the definition catalogue, the expression and function catalogues, the task authorization, the options of every engine section. Every store has an in-memory or fail-closed default that a store library replaces.
AddWorkflowPostgresDataStore(configuration)StellaOps.Workflow.DataStore.PostgreSQLThe PostgreSQL stores, the startup migration of the workflow schema, the native signal driver. Registered only when WorkflowBackend:Provider is Postgres (the default).
AddWorkflowMongoDataStore(configuration)StellaOps.Workflow.DataStore.MongoDBThe MongoDB stores. Registered only when WorkflowBackend:Provider is Mongo.
AddWorkflowEngineHostedServices()StellaOps.Workflow.EngineThe signal pump, the retention job and the licence monitor, and the informational licence health entry.
ValidateWorkflowProviderRegistrations(configuration)StellaOps.Workflow.EngineA start-up check: it throws when the selected backend or signal driver was not registered by any library. Call it after every store and driver registration.
AddWorkflowRegistration<TWorkflow, TStartRequest>()StellaOps.Workflow.AbstractionsOne workflow. On Stella.Engine it is compiled to its canonical definition when the host starts, and a workflow that does not compile stops the start.
AddWorkflowAuthorization()StellaOps.Workflow.AspNetCoreThe three authorization policies of the endpoints.
MapWorkflowEndpoints()StellaOps.Workflow.AspNetCoreThe HTTP API under /api/workflow. Returns the route group, so you can add your own filters, metadata or rate limits.

A worker host without HTTP uses the same registrations except the last two, and calls the engine services directly (Human tasks and the HTTP API).

Order of the registrations

  1. AddWorkflowEngineCoreServices first: it adds the defaults with TryAdd.
  2. Then the store, the signal driver and the transports: they replace the defaults.
  3. Then ValidateWorkflowProviderRegistrations.
  4. Your own replacements of engine services (for example an actor resolver of your own) after the engine registrations and AddWorkflowAuthorization, so that they are the last registration of their service type.

The runtime provider

The engine has two runtime providers:

ProviderRuns a builder workflow fromRuns
Stella.Engine (the default)Its canonical definition: the document the engine validates, stores, renders and exportsEvery expression-based step of the C# builder, not Run or a C# delegate; maps and external activities need the durable services
Stella.InProcessIts C# specification, in the processCalls, decisions, human tasks, child workflows and inline Run code; no fork, map, external activity, timer, external signal or task deadline

WorkflowRuntime:DefaultProvider selects the provider; a host that sets nothing runs Stella.Engine. To select the in-process provider:

{ "WorkflowRuntime": { "DefaultProvider": "Stella.InProcess" } }
WorkflowRuntime__DefaultProvider=Stella.InProcess

The host checks the choice when it starts, and stops with a message when:

The runtime status of an instance differs: on Stella.Engine it reads WaitingForTask or WaitingForSignal, and the runtime state is the engine’s snapshot (version, workflowState, waitings, …); on Stella.InProcess it reads Open, with the plain workflow state.

The provider is stored with each instance, but only the resumption from a signal (a timer, an external signal, a child workflow) uses the stored provider. A start and a task completion use the provider configured at that moment, so an instance that is open when you change the setting continues partly on the new provider. Choose the provider before the first instance starts, and keep it.

Authentication

The package does not choose an authentication scheme. Register any ASP.NET Core scheme whose principal carries the caller’s scopes, then AddWorkflowAuthorization():

// JWT bearer tokens (Authentication:Schemes:Bearer). The workflow scopes travel in the `scope`
// claim; MapInboundClaims = false keeps the claim names of the token.
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => options.MapInboundClaims = false);

// The three Workflow policies, and the actor of a task action taken from the token: the actor ID from
// `sub` and the roles from the `role` claims (WorkflowAuthorization:ActorIdClaimTypes, RoleClaimTypes).
builder.Services.AddWorkflowAuthorization();

AddJwtBearer reads Authentication:Schemes:Bearer. For tokens of an OpenID Connect provider:

{
  "Authentication": {
    "Schemes": {
      "Bearer": {
        "Authority": "https://login.contoso.example/realms/operations",
        "ValidAudiences": [ "workflow-host" ]
      }
    }
  }
}

MapInboundClaims = false keeps the claim names of the token (sub, scope, role). With the default mapping the handler renames sub and role to the .NET claim types; the default actor and role claim types below cover both names. It also renames scp, and the policies read only scope and scp: with a token that carries its scopes in scp, set MapInboundClaims = false.

Scopes and policies

Every endpoint requires one of three policies. A policy is satisfied by any of its scopes, read from space-delimited scope claims and from individual scp claims, compared without regard to case:

PolicyScopes that satisfy itEndpoints
workflow.viewworkflow:view, workflow:operate, workflow:adminEvery GET, and the read-only POST routes (export, canonical validation)
workflow.operateworkflow:operate, workflow:adminStart, task actions, raising a signal
workflow.adminworkflow:adminImport and activation of definitions, retention, dead-letter replay

A request without a valid token gets 401; a token without a matching scope gets 403. The constants are WorkflowPolicies.View, Operate, Admin and WorkflowPolicies.ViewScope, OperateScope, AdminScope.

To use your own scope names, call AddWorkflowAuthorization (it also registers the claims actor resolver and binds WorkflowAuthorization), then register the policies workflow.view, workflow.operate and workflow.admin again with your requirements, for example in services.AddAuthorization(options => options.AddPolicy(WorkflowPolicies.View, ...)): the later registration of a policy name replaces the earlier one.

The actor of a task action

The task actions (complete, assign, release) act as the authenticated caller. AddWorkflowAuthorization registers a resolver that reads the actor ID and the actor’s roles from the principal’s claims; an actorId or actorRoles sent in the request body is not used.

SettingDefaultMeaning
WorkflowAuthorization:ActorIdClaimTypessub, then the name identifier claimClaim types read for the actor ID, in order; the first non-blank value wins
WorkflowAuthorization:RoleClaimTypesthe role claim (ClaimTypes.Role) and roleClaim types whose values are the actor’s roles

A non-empty list replaces the defaults. For a provider that puts the user in oid and the roles in groups:

{
  "WorkflowAuthorization": {
    "ActorIdClaimTypes": [ "oid" ],
    "RoleClaimTypes": [ "groups" ]
  }
}

The same lists can be set in code with AddWorkflowAuthorization(options => ...).

SituationAnswer
The token has no actor ID claim403 with error: WorkflowActorUnresolved
The permission evaluator refuses the action403 with error: WorkflowTaskActionDenied

The definition import and activation record the caller as the importer and the activation actor, and a start, a signal and a task action make the caller the caller of the services the workflow calls in that request.

Cases:

Health and readiness

AddWorkflowEngineHostedServices registers the health checks service and the licence entry. Map a liveness and a readiness endpoint:

// Liveness: the process answers. Readiness: every health check, written with the Workflow
// response writer, which shows the informational `licence` entry with its data.
app.MapHealthChecks("/healthz", new HealthCheckOptions { Predicate = _ => false }).AllowAnonymous();
app.MapHealthChecks("/readyz", new HealthCheckOptions { ResponseWriter = WorkflowHealthResponseWriter.WriteAsync })
    .AllowAnonymous();

WorkflowHealthResponseWriter.WriteAsync writes a JSON report with each entry’s status and data:

{
  "status": "Healthy",
  "entries": {
    "licence": {
      "status": "Healthy",
      "description": "Recorded workflow-name count: 2.",
      "data": {
        "status": "within-free-limit",
        "designatedWorkflows": 2,
        "ledger": "durable",
        "freeLimit": 50,
        "informational": true,
        "licenceFilesLoaded": 0,
        "notice": { "case": "no-licence-file" }
      }
    }
  }
}

The example is abridged; the entry’s data also carries the evaluation time, the explanation and the full notice (Licensing). The entry carries a status from the first evaluation, a few seconds after the host starts.

The licence entry always reports Healthy: the licence status is information, never a readiness condition. Add your own checks (the database, Redis) with AddHealthChecks().Add...; they appear in the same report.

Endpoints

// Every Workflow endpoint under /api/workflow, each behind one of the View, Operate and Admin policies.
app.MapWorkflowEndpoints();

MapWorkflowEndpoints returns the route group (RouteGroupBuilder), so the host can add its own conventions to every Workflow endpoint at once: a rate-limiting policy (RequireRateLimiting), an endpoint filter (AddEndpointFilter), CORS, or OpenAPI tags.

Each state-changing endpoint carries a WorkflowEndpointOperation metadata entry (an operation name and a resource type). The package writes no audit record; a host that needs one reads the metadata in an endpoint filter and writes its own. The routes are listed in Human tasks and the HTTP API.

GET /api/workflow/metadata reports the host’s application name as serviceName.

Plugins instead of package references

Each store, signal driver and transport library also carries a plugin routine (IDependencyInjectionRoutine). A host that loads libraries from a plugin folder registers them through the routine instead of calling the extension method; the routine calls the same method. Load the store before the transports and the workflow assemblies.

Production checklist

Pitfalls