Lesson 2: Service tasks

A workflow calls services: it reads the stock level of an item, and below the reorder level it places a purchase order. A failed order opens a task for a planner.

An endpoint call with a result

// An `endpoint` call: the service name resolves through WorkflowEndpointTransport:Services.
// The response is kept under "result.stock" for the following steps.
.Call<object>(
    "Read stock level",
    new EndpointAddress("inventory", "/items/stock-level"),
    WorkflowExpr.Obj(WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku"))),
    resultKey: "stock")
.Set("onHand", WorkflowExpr.Path("result.stock.onHand"))

An http call with failure and timeout branches

// An `http` call: the target resolves through WorkflowHttpTransport:Targets.
// A failed or unreachable call runs whenFailure, a timed-out call whenTimeout;
// "result.lastFailure" describes the failure.
.Call(
    "Place purchase order",
    new HttpAddress("purchasing", "/purchase-orders"),
    WorkflowExpr.Obj(
        WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku")),
        WorkflowExpr.Prop("quantity", WorkflowExpr.Path("state.reorderQuantity"))),
    whenFailure: failed => failed
        .Set("orderFailure", WorkflowExpr.Path("result.lastFailure.message"))
        .ActivateTask("Place order manually"),
    whenTimeout: timedOut => timedOut
        .Set("orderFailure", WorkflowExpr.String("the purchasing service did not answer"))
        .ActivateTask("Place order manually"))

Registering the transports

/// <summary>Registers a transport for each address kind the host's workflows use.</summary>
public static IServiceCollection AddWorkflowTransports(this IServiceCollection services, IConfiguration configuration)
{
    // `endpoint` (WorkflowEndpointTransport:Services) and `http` (WorkflowHttpTransport:Targets).
    services.AddWorkflowHttpTransport(configuration);

    // `graphql` (WorkflowGraphqlTransport:Targets).
    services.AddWorkflowGraphqlTransport(configuration);

    // `rabbit` (WorkflowRabbitTransport): one broker connection per host.
    services.AddWorkflowRabbitTransport(configuration);

    return services;
}

A graphql call with variables

SupplierLookupWorkflow (complete code below) asks a GraphQL API for the supplier of an item. The variables are an expression:

// A `graphql` call: the target resolves through WorkflowGraphqlTransport:Targets. The
// variables are an expression; the response body ({ "data": ... }) is kept under "result.supplier".
.QueryGraphql<object>(
    "Find supplier",
    new GraphqlAddress(
        "catalogue",
        "query Supplier($sku: String!) { supplier(sku: $sku) { id name } }",
        "Supplier"),
    WorkflowExpr.Obj(WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku"))),
    resultKey: "supplier")
.Set("supplierName", WorkflowExpr.Path("result.supplier.data.supplier.name"))

A rabbit command and a publish

StockReservationWorkflow reserves stock through a RabbitMQ consumer and waits for its reply, at most 30 seconds:

// A `rabbit` command: the consumer of the exchange "inventory" and the routing key
// "stock.reserve" answers with a correlated reply, kept under "result.reservation".
// The step gives up after 30 seconds and runs its timeout branch.
.Call<object>(
    "Reserve stock",
    new RabbitAddress("inventory", "stock.reserve", "ReserveStock"),
    WorkflowExpr.Obj(
        WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku")),
        WorkflowExpr.Prop("quantity", WorkflowExpr.Path("state.quantity"))),
    whenFailure: failed => failed
        .Set("reservation", WorkflowExpr.String("failed"))
        .Complete(),
    whenTimeout: timedOut => timedOut
        .Set("reservation", WorkflowExpr.String("timed-out"))
        .Complete(),
    resultKey: "reservation",
    timeoutSeconds: 30)

Then it announces the reservation with a plain publish:

// A plain publish: no command, no reply; the call succeeds when the broker confirms it.
.Call(
    "Announce reservation",
    new RabbitAddress("inventory", "stock.reserved"),
    WorkflowExpr.Obj(WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId"))))

Concepts

  • The definition names a service (inventory) or a target (purchasing); the host’s configuration gives the URL (Calling services).
  • resultKey: "stock" keeps the response under result.stock; Set copies what the workflow keeps.
  • A failed or unreachable call runs whenFailure, a timed-out call whenTimeout; timeoutSeconds sets the step’s timeout. In the branch, result.lastFailure describes the failure (Calling services).
  • A graphql call is written with QueryGraphql, its variables as an expression, and a rabbit call with a RabbitAddress (Calling services).

The complete code

The lesson’s complete code. It uses the namespace of the tutorials; put the classes in a namespace of yours.

InventoryRestockWorkflow.cs:

using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;

namespace Examples.Workflow.Tutorials.ServiceTasks;

public sealed class InventoryRestockRequest
{
    [WorkflowBusinessId]
    public string Sku { get; set; } = string.Empty;

    public int ReorderLevel { get; set; }

    public int ReorderQuantity { get; set; }
}

/// <summary>
/// Reads the stock level of an item from the inventory service. Below the reorder level, it places a
/// purchase order with the purchasing service; a failed order opens a task for a planner.
/// </summary>
public sealed class InventoryRestockWorkflow : IDeclarativeWorkflow<InventoryRestockRequest>
{
    public string WorkflowName => "InventoryRestock";

    public string WorkflowVersion => "1.0.0";

    public string DisplayName => "Inventory restock";

    public IReadOnlyCollection<string> WorkflowRoles { get; } = ["inventory-planner"];

    public WorkflowSpec<InventoryRestockRequest> Spec { get; } = WorkflowSpec.For<InventoryRestockRequest>()
        .InitializeState(
            WorkflowExpr.Obj(
                WorkflowExpr.Prop("sku", WorkflowExpr.Path("start.sku")),
                WorkflowExpr.Prop("reorderLevel", WorkflowExpr.Path("start.reorderLevel")),
                WorkflowExpr.Prop("reorderQuantity", WorkflowExpr.Path("start.reorderQuantity"))))
        .AddTask(
            WorkflowHumanTask.For<InventoryRestockRequest>("Place order manually", "ManualPurchaseOrder", "inventory/orders")
                .WithPayload(
                    WorkflowExpr.Obj(
                        WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku")),
                        WorkflowExpr.Prop("failure", WorkflowExpr.Path("state.orderFailure"))))
                .OnComplete(flow => flow.Complete()))
        .StartWith(flow => flow
            // An `endpoint` call: the service name resolves through WorkflowEndpointTransport:Services.
            // The response is kept under "result.stock" for the following steps.
            .Call<object>(
                "Read stock level",
                new EndpointAddress("inventory", "/items/stock-level"),
                WorkflowExpr.Obj(WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku"))),
                resultKey: "stock")
            .Set("onHand", WorkflowExpr.Path("result.stock.onHand"))
            .WhenExpression(
                "Below the reorder level?",
                WorkflowExpr.Lt(WorkflowExpr.Path("state.onHand"), WorkflowExpr.Path("state.reorderLevel")),
                reorder => reorder
                    // An `http` call: the target resolves through WorkflowHttpTransport:Targets.
                    // A failed or unreachable call runs whenFailure, a timed-out call whenTimeout;
                    // "result.lastFailure" describes the failure.
                    .Call(
                        "Place purchase order",
                        new HttpAddress("purchasing", "/purchase-orders"),
                        WorkflowExpr.Obj(
                            WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku")),
                            WorkflowExpr.Prop("quantity", WorkflowExpr.Path("state.reorderQuantity"))),
                        whenFailure: failed => failed
                            .Set("orderFailure", WorkflowExpr.Path("result.lastFailure.message"))
                            .ActivateTask("Place order manually"),
                        whenTimeout: timedOut => timedOut
                            .Set("orderFailure", WorkflowExpr.String("the purchasing service did not answer"))
                            .ActivateTask("Place order manually"))
                    .Set("ordered", WorkflowExpr.Bool(true))
                    .Complete(),
                enough => enough
                    .Set("ordered", WorkflowExpr.Bool(false))
                    .Complete()))
        .Build();

    public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}

SupplierLookupWorkflow.cs:

using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;

namespace Examples.Workflow.Tutorials.ServiceTasks;

public sealed class SupplierLookupRequest
{
    [WorkflowBusinessId]
    public string Sku { get; set; } = string.Empty;
}

/// <summary>Looks up the supplier of an item with a GraphQL query that takes the item as a variable.</summary>
public sealed class SupplierLookupWorkflow : IDeclarativeWorkflow<SupplierLookupRequest>
{
    public string WorkflowName => "SupplierLookup";

    public string WorkflowVersion => "1.0.0";

    public string DisplayName => "Supplier lookup";

    public IReadOnlyCollection<string> WorkflowRoles { get; } = ["inventory-planner"];

    public WorkflowSpec<SupplierLookupRequest> Spec { get; } = WorkflowSpec.For<SupplierLookupRequest>()
        .InitializeState(WorkflowExpr.Obj(WorkflowExpr.Prop("sku", WorkflowExpr.Path("start.sku"))))
        .StartWith(flow => flow
            // A `graphql` call: the target resolves through WorkflowGraphqlTransport:Targets. The
            // variables are an expression; the response body ({ "data": ... }) is kept under "result.supplier".
            .QueryGraphql<object>(
                "Find supplier",
                new GraphqlAddress(
                    "catalogue",
                    "query Supplier($sku: String!) { supplier(sku: $sku) { id name } }",
                    "Supplier"),
                WorkflowExpr.Obj(WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku"))),
                resultKey: "supplier")
            .Set("supplierName", WorkflowExpr.Path("result.supplier.data.supplier.name"))
            .Complete())
        .Build();

    public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}

StockReservationWorkflow.cs:

using StellaOps.Workflow.Abstractions;
using StellaOps.Workflow.Contracts;

namespace Examples.Workflow.Tutorials.ServiceTasks;

public sealed class StockReservationRequest
{
    [WorkflowBusinessId]
    public string OrderId { get; set; } = string.Empty;

    public string Sku { get; set; } = string.Empty;

    public int Quantity { get; set; }
}

/// <summary>
/// Reserves stock through a RabbitMQ consumer and announces the reservation: a command with a reply,
/// then a plain publish.
/// </summary>
public sealed class StockReservationWorkflow : IDeclarativeWorkflow<StockReservationRequest>
{
    public string WorkflowName => "StockReservation";

    public string WorkflowVersion => "1.0.0";

    public string DisplayName => "Stock reservation";

    public IReadOnlyCollection<string> WorkflowRoles { get; } = ["inventory-planner"];

    public WorkflowSpec<StockReservationRequest> Spec { get; } = WorkflowSpec.For<StockReservationRequest>()
        .InitializeState(
            WorkflowExpr.Obj(
                WorkflowExpr.Prop("orderId", WorkflowExpr.Path("start.orderId")),
                WorkflowExpr.Prop("sku", WorkflowExpr.Path("start.sku")),
                WorkflowExpr.Prop("quantity", WorkflowExpr.Path("start.quantity"))))
        .StartWith(flow => flow
            // A `rabbit` command: the consumer of the exchange "inventory" and the routing key
            // "stock.reserve" answers with a correlated reply, kept under "result.reservation".
            // The step gives up after 30 seconds and runs its timeout branch.
            .Call<object>(
                "Reserve stock",
                new RabbitAddress("inventory", "stock.reserve", "ReserveStock"),
                WorkflowExpr.Obj(
                    WorkflowExpr.Prop("sku", WorkflowExpr.Path("state.sku")),
                    WorkflowExpr.Prop("quantity", WorkflowExpr.Path("state.quantity"))),
                whenFailure: failed => failed
                    .Set("reservation", WorkflowExpr.String("failed"))
                    .Complete(),
                whenTimeout: timedOut => timedOut
                    .Set("reservation", WorkflowExpr.String("timed-out"))
                    .Complete(),
                resultKey: "reservation",
                timeoutSeconds: 30)
            // A plain publish: no command, no reply; the call succeeds when the broker confirms it.
            .Call(
                "Announce reservation",
                new RabbitAddress("inventory", "stock.reserved"),
                WorkflowExpr.Obj(WorkflowExpr.Prop("orderId", WorkflowExpr.Path("state.orderId"))))
            .Complete())
        .Build();

    public IReadOnlyCollection<WorkflowTaskDescriptor> Tasks => Spec.TaskDescriptors;
}

TransportRegistrations.cs:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using StellaOps.Workflow.Transport.GraphQL;
using StellaOps.Workflow.Transport.Http;
using StellaOps.Workflow.Transport.RabbitMq;

namespace Examples.Workflow.Tutorials.ServiceTasks;

public static class TransportRegistrations
{
    /// <summary>Registers a transport for each address kind the host's workflows use.</summary>
    public static IServiceCollection AddWorkflowTransports(this IServiceCollection services, IConfiguration configuration)
    {
        // `endpoint` (WorkflowEndpointTransport:Services) and `http` (WorkflowHttpTransport:Targets).
        services.AddWorkflowHttpTransport(configuration);

        // `graphql` (WorkflowGraphqlTransport:Targets).
        services.AddWorkflowGraphqlTransport(configuration);

        // `rabbit` (WorkflowRabbitTransport): one broker connection per host.
        services.AddWorkflowRabbitTransport(configuration);

        return services;
    }
}

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 InventoryRestockWorkflow(), "inventory-restock.definition.json");
  • CanonicalExport.WriteCanonicalJson(new SupplierLookupWorkflow(), "supplier-lookup.definition.json");
  • CanonicalExport.WriteCanonicalJson(new StockReservationWorkflow(), "stock-reservation.definition.json");

Next: Lesson 3: Decisions.