Step 7: When a step fails for good
A step can end without the value the order needs in two ways. The external system can answer that it cannot do what was asked, such as a warehouse with no stock. Or the call can throw until the retry policy gives up, and then the step fails. This step returns the answer as a value, catches a failure that has an answer in the domain, and lets a failure that has none end the order.
This page changes the program from step 6.
Return an answer as a value
A warehouse that has no stock has answered, and a second call gets the same answer. FCQRS stores whatever an activity returns as the step's result. The policy retries only a call that throws.
In Order.fs (Order.cs), replace the services. Reserve returns a StockAnswer, and the
carrier is told what it ships:
Shared setup
module Account =
open FCQRS.Common
// What the program and the order workflow can ask an account to do.
type AccountCommand =
| Deposit of amount: decimal
| Debit of payment: string * amount: decimal
// What the account replies. Rejected is a reply only: it is never stored.
type AccountEvent =
| Deposited of amount: decimal
| Debited of payment: string * amount: decimal
| Rejected of reason: string
// What the account knows now. Payments holds the payments it has taken, so
// a repeated debit takes the money once.
type AccountState = { Balance: decimal; Payments: Set<string> }
// The state before the account's first event.
let initial = { Balance = 0m; Payments = Set.empty }
// Chooses what to do with a command, based on the current state.
let decide (command: Command<AccountCommand>) (state: AccountState) =
match command.CommandDetails with
| Deposit amount -> PersistEvent(Deposited amount)
// A repeated debit gets the first answer. It is checked before the
// balance, because the first debit has already lowered the balance.
| Debit(payment, amount) when state.Payments.Contains payment ->
DeferEvent(Debited(payment, amount))
| Debit(_, amount) when amount > state.Balance ->
DeferEvent(Rejected $"Insufficient funds: {state.Balance} available")
| Debit(payment, amount) -> PersistEvent(Debited(payment, amount))
// Applies one event. A rejection or a repeated reply changes nothing.
let fold (event: Event<AccountEvent>) (state: AccountState) =
match event.EventDetails with
| Deposited amount -> { state with Balance = state.Balance + amount }
| Debited(payment, _) when state.Payments.Contains payment -> state
| Debited(payment, amount) ->
{ state with
Balance = state.Balance - amount
Payments = state.Payments.Add payment
}
| Rejected _ -> state
module Order =
open System
open System.Threading.Tasks
open FCQRS.Common
open FCQRS.FSharp
open FCQRS.Workflows
open Account
// Unchanged from step 6.
type OrderRequest = {
Customer: string
Item: string
Quantity: int
UnitPrice: decimal
}
type OrderResult = {
Status: string
Reservation: string
Shipment: string
Confirmation: Guid
PlacedAt: DateTime
}
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.AccountFCQRSFCQRS.CommonContains common types like Events and Commands Functionality for Write Side.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountCommandDepositamount: decimaldecimalAn abbreviation for the CLI type . Basic Types
Debitpayment: stringstringAn abbreviation for the CLI type . Basic Types
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountEventDepositedDebitedRejectedreason: stringFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountStateBalance: decimalPayments: Set<string>Microsoft.FSharp.Collections.FSharpSet`1Immutable sets based on binary trees, where elements are ordered by F# generic comparison. By default comparison is the F# structural comparison function or uses implementations of the IComparable interface on element values. See the module for further operations on sets. All members of this class are thread-safe and may be used concurrently from multiple threads.
initial: AccountStateMicrosoft.FSharp.Collections.SetModuleContains operations for working with values of type .
empty: Set<'T>The empty set for the type 'T. Set.empty<int> Evaluates to set [ ]. This is an O(1) operation.
decide: Command<AccountCommand> -> AccountState -> EventAction<AccountEvent>command: Command<AccountCommand>FCQRS.Common.Command`1Represents a command to be processed by an aggregate actor. <typeparam name="'CommandDetails">The specific type of the command payload.</typeparam>
state: AccountStateCommandDetails: 'CommandDetailsThe specific details or payload of the command.
PersistEventPersist the event to the journal. The actor's state will be updated using the event handler *after* persistence succeeds.
Contains: string -> boolA useful shortcut for Set.contains. See the Set module for further operations on sets. The value to check. True if the set contains value. let set = Set.empty.Add(2).Add(3) printfn $"Does the set contain 1? {set.Contains(1)}" The sample evaluates to the following output: Does the set contain 1? false This is an O(log n) operation, where n is the number of elements in the set.
DeferEventPublish and fold the event in the live actor without storing it or incrementing the persisted version. A deferred event does not start a saga; running sagas still receive it.
(>): 'T -> 'T -> boolStructural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false
fold: Event<AccountEvent> -> AccountState -> AccountStateevent: Event<AccountEvent>FCQRS.Common.Event`1Represents an event generated by an aggregate actor as a result of processing a command. <typeparam name="'EventDetails">The specific type of the event payload.</typeparam>
EventDetails: 'EventDetailsThe specific details or payload of the event.
(-): ^T1 -> ^T2 -> ^T3Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8
Add: string -> Set<string>A useful shortcut for Set.add. Note this operation produces a new set and does not mutate the original set. The new set will share many storage nodes with the original. See the Set module for further operations on sets. The value to add to the set. The result set. let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The new set is: {set}" The sample evaluates to the following output: The new set is: set [1; 2] This is an O(log n) operation, where n is the number of elements in the set.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.OrderSystemThreadingTasksFCQRS.FSharpIdiomatic-F# functional facade for FCQRS. Gives F# consumers the same one-call ergonomics the C# host-builder (HostExtensions.fs) gives C#, but with F# idioms: records-of-functions for the definitions, typed handles for the results, an explicit wiring pipeline, and plain helpers for saga side effects. It is a *pure addition* that wraps only the existing primitives (IActor.InitializeActor / SagaBuilder.initSimple / Projections.startTracked / InitializeSagaStarter / CreateCommandSubscription / Actor.api) and changes nothing in the C# interop layer or the core. open FCQRS.FSharp let api = Fcqrs.actor config loggerFactory (Some (Fcqrs.connect DBType.Sqlite conn)) "Cluster" let documents = Fcqrs.aggregate api { Name="Document"; Initial=...; Decide=...; Fold=... } let slugs = Fcqrs.aggregate api { Name="Slug"; Initial=...; Decide=...; Fold=... } let publication = Fcqrs.saga api (publicationDef documents.Factory slugs.Factory) Fcqrs.wireSagaStarters api [ publication ] let subs = Fcqrs.projection api (Projection.single 0 updateReadModel) // (Projection.multi when you must control which notifications publish) // send a command and await the matching aggregate reply: let! ev = documents.Send (Fcqrs.newCid()) (Fcqrs.aggregateId id) cmd (fun e -> ...)
WorkflowsFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.OrderRequestCustomer: stringItem: stringQuantity: intintAn abbreviation for the CLI type . Basic Types
UnitPrice: decimalFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.OrderResultStatus: stringReservation: stringShipment: stringConfirmation: GuidSystem.GuidRepresents a globally unique identifier (GUID).
PlacedAt: DateTimeSystem.DateTimeRepresents an instant in time, typically expressed as a date and time of day.
// What the warehouse answers when it is asked for stock. FCQRS stores the
// answer as the step's result.
type StockAnswer =
| Reserved of reservation: string
| OutOfStock
// The warehouse is an external system. The key is the same for every
// attempt of one step, so the warehouse can recognise a repeated call.
type IWarehouse =
abstract Reserve:
key: string * item: string * quantity: int -> Task<StockAnswer>
abstract Release: key: string * reservation: string -> Task<string>
// The carrier is another external system. It returns a shipment ID.
type ICarrier =
abstract Ship:
key: string * reservation: string * item: string -> Task<string>
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.StockAnswerReservedreservation: stringstringAn abbreviation for the CLI type . Basic Types
OutOfStockFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.IWarehouseReserve: IWarehouse -> string * string * int -> Task<StockAnswer>keyitemquantityintAn abbreviation for the CLI type . Basic Types
System.Threading.Tasks.Task`1Represents an asynchronous operation that can return a value. The type of the result produced by this .
Release: IWarehouse -> string * string -> Task<string>reservationFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.ICarrierShip: ICarrier -> string * string * string -> Task<string>// What the warehouse answers when it is asked for stock. FCQRS stores the
// answer as the step's result.
public union StockAnswer(Reserved, OutOfStock);
public sealed record Reserved(string Reservation);
public sealed record OutOfStock;
// The warehouse is an external system. The key is the same for every
// attempt of one step, so the warehouse can recognise a repeated call.
public interface IWarehouse
{
Task<StockAnswer> Reserve(string key, string item, int quantity);
Task<string> Release(string key, string reservation);
}
// The carrier is another external system. It returns a shipment ID.
public interface ICarrier
{
Task<string> Ship(string key, string reservation, string item);
}
In step 6, reserve-stock stored a string. It now stores a StockAnswer, and the type of a
stored result is a persistent contract: this code would park an order whose journal holds the
string. This step starts from an empty database.
Catch the failure that has an answer
When a step's policy gives up, FCQRS stores the failure as the step's result, and the body sees a
WorkflowStepFailedException. On a replay the body sees the same exception again, from the
stored failure, without running the step.
Replace the workflow. The steps after the reservation move into fulfil (in C#, Fulfil). The
body reserves the stock inside a try, returns a result for OutOfStock, and runs fulfil for
Reserved. The approval now waits up to one day, and the carrier gets the item.
An order with reserved stock can still be refused twice: by the approval and by the payment. In
F#, approval and debit each give a Result, and fulfil runs them, the packing timer, and
ship in a workflowResult block. A do! or let! on a step that gives an Error ends the
block with that Error, so the steps below it do not run. release-stock then runs in one place,
whichever step refused. C# has no such builder. Its Fulfil returns after each refusal, as in
step 6:
Shared setup
let reserveRetry = Retry.times 5 (System.TimeSpan.FromSeconds 10.0)
let callRetry = Retry.times 3 (System.TimeSpan.FromSeconds 10.0)
reserveRetry: RetryPolicyFCQRS.Workflows.RetryCommon retry policies.
times: int -> TimeSpan -> RetryPolicyAt most `attempts` attempts, with backoff from one second to one minute. Each attempt fails when it has not finished within `attemptTimeout`.
SystemFromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
System.TimeSpanRepresents a time interval.
callRetry: RetryPolicy// "order" is stored with every instance. It must not change.
let definition
(warehouse: IWarehouse)
(carrier: ICarrier)
(accounts: AggregateHandle<AccountCommand, AccountEvent>)
=
// The result of an order that reserved no stock.
let unfilled status = {
Status = status
Reservation = ""
Shipment = ""
Confirmation = Guid.Empty
PlacedAt = DateTime.MinValue
}
// The rest of an order, once its stock is reserved.
let fulfil (request: OrderRequest) (reservation: string) =
workflow {
// The body must give the same answers on every replay, so it
// reads the clock and makes GUIDs only through steps. FCQRS
// stores their values and replays them.
let! placedAt = now
let! confirmation = newGuid
let finish status shipment = {
Status = status
Reservation = reservation
Shipment = shipment
Confirmation = confirmation
PlacedAt = placedAt
}
let total = request.UnitPrice * decimal request.Quantity
// An order over 1000 waits for a person to approve it, for at
// most one day. With no answer by then, the wait returns None.
let approvalWait = TimeSpan.FromDays 1.0
let approval =
workflow {
if total <= 1000m then
return Ok()
else
let! answer =
waitSignalFor<bool> "approval" approvalWait
if defaultArg answer false then
return Ok()
else
return Error "not approved"
}
// The confirmation number identifies the payment, so a
// repeated debit is recognised as the same payment.
let payment = string confirmation
let debit =
workflow {
let! reply =
send accounts request.Customer (Debit(payment, total))
match reply with
| Rejected _ -> return Error "payment refused"
| _ -> return Ok()
}
// A step that gives an Error ends this block with it. An order
// that is not approved is not charged, and an order that is
// not paid for does not ship.
let! shipped =
workflowResult {
do! approval
do! debit
// Packing takes two seconds. The timer's due time is
// stored, so a restart does not start the wait again.
do! sleep (TimeSpan.FromSeconds 2.0)
return!
activity "ship" callRetry (fun attempt ->
carrier.Ship(
attempt.IdempotencyKey,
reservation,
request.Item))
}
match shipped with
| Ok shipment -> return finish "shipped" shipment
| Error status ->
// An Error is a value, so no handler runs for it. The stock
// is given back here, whichever step refused.
let! _ =
activity "release-stock" reserveRetry (fun attempt ->
warehouse.Release(attempt.IdempotencyKey, reservation))
return finish status ""
}
Workflow.define "order" (fun (request: OrderRequest) ->
workflow {
try
// A failed attempt is not stored. FCQRS tries again until
// an attempt succeeds or the policy gives up.
let! answer =
activity "reserve-stock" reserveRetry (fun attempt ->
warehouse.Reserve(
attempt.IdempotencyKey,
request.Item,
request.Quantity))
// An answer is the step's result, whichever case it is. It
// is stored, and the policy does not retry it.
match answer with
| OutOfStock -> return unfilled "out of stock"
| Reserved reservation -> return! fulfil request reservation
// When a step's policy gives up, the step fails, and the body
// sees WorkflowStepFailedException. A warehouse that was busy at
// every attempt reserved nothing, so the order can end with a
// result. Any other failure is not caught.
with :? WorkflowStepFailedException as failed
when failed.StepName = "reserve-stock" ->
return unfilled "warehouse unavailable"
})
definition: IWarehouse -> ICarrier -> AggregateHandle<AccountCommand,AccountEvent> -> WorkflowDefinition<OrderRequest,OrderResult>warehouse: IWarehouseFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.IWarehousecarrier: ICarrierFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.ICarrieraccounts: AggregateHandle<AccountCommand,AccountEvent>FCQRS.FSharp.AggregateHandle`2What you get back after registering an aggregate.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountCommandFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountEventunfilled: string -> OrderResultstatus: stringStatus: stringReservation: stringShipment: stringConfirmation: GuidSystem.GuidRepresents a globally unique identifier (GUID).
Empty: GuidA read-only instance of the structure whose value is all zeros.
PlacedAt: DateTimeSystem.DateTimeRepresents an instant in time, typically expressed as a date and time of day.
MinValue: DateTimeRepresents the smallest possible value of . This field is read-only.
fulfil: OrderRequest -> string -> Workflow<OrderResult>request: OrderRequestFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.OrderRequestreservation: stringstringAn abbreviation for the CLI type . Basic Types
workflow: WorkflowBuilderBuilds a workflow: `workflow { let! x = activity ... }`.
placedAt: DateTimenow: Workflow<DateTime>The current UTC time, stored so that replay returns the same value.
confirmation: GuidnewGuid: Workflow<Guid>A new GUID, stored so that replay returns the same value.
finish: string -> string -> OrderResultshipment: stringtotal: decimalUnitPrice: decimal(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
decimal: ^T -> decimalConverts the argument to System.Decimal using a direct conversion for all primitive numeric types. For strings, the input is converted using UInt64.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted decimal. decimal "42.23" // evaluates to 42.23M decimal 0xff // evaluates to 255M decimal -10 // evaluates to -10M
Quantity: intapprovalWait: TimeSpanSystem.TimeSpanRepresents a time interval.
FromDays: float -> TimeSpanReturns a that represents a specified number of days, where the specification is accurate to the nearest millisecond. A number of days, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
approval: Workflow<Result<unit,string>>(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
OkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
answer: bool optionwaitSignalFor: string -> TimeSpan -> Workflow<'T option>Waits for a signal named `name` for at most `timeout`, measured from the stored start of the step. Gives `None` when the time passes first; a signal that arrives later stays stored for the next wait.
boolAn abbreviation for the CLI type . Basic Types
defaultArg: 'T option -> 'T -> 'TUsed to specify a default value for an optional argument in the implementation of a function An option representing the argument. The default value of the argument. The argument value. If it is None, the defaultValue is returned. type Vector(x: double, y: double, ?z: double) = let z = defaultArg z 0.0 member this.X = x member this.Y = y member this.Z = z let v1 = Vector(1.0, 2.0) v1.Z // Evaluates to 0. let v2 = Vector(1.0, 2.0, 3.0) v2.Z // Evaluates to 3.0
ErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
payment: stringstring: 'T -> stringConverts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattable, ToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10"
debit: Workflow<Result<unit,string>>reply: AccountEventsend: AggregateHandle<'Command,'Event> -> string -> 'Command -> Workflow<'Event>`sendWith` under `Retry.command`: send again when no reply came in time, with backoff, for five minutes.
Customer: stringDebitRejectedshipped: Result<string,string>workflowResult: WorkflowResultBuilderBuilds a workflow that gives a `Result`. A `let!` on a step that gives an `Error` ends the block with it: `workflowResult { let! reservation = reserve ... }`.
sleep: TimeSpan -> Workflow<unit>Waits for `duration`. The due time is stored when the step is first reached, so a restart does not postpone it.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
activity: string -> RetryPolicy -> (AttemptContext -> Task<'T>) -> Workflow<'T>Calls an external system. The call runs at least once: a crash after the call and before its result is stored repeats it, so pass `IdempotencyKey` to the external system. `name` is stored and must not change while instances are running. The policy needs an `AttemptTimeout` or a `Deadline`: an attempt with neither would wait as long as its call, also for a call that ignores its cancellation token.
callRetry: RetryPolicyattempt: AttemptContextShip: string * string * string -> Task<string>IdempotencyKey: stringThe same for every attempt of this step, across restarts: workflow name, workflow ID, and step path. Pass it to the external system so a repeated call is recognised.
Item: stringreserveRetry: RetryPolicyRelease: string * string -> Task<string>FCQRS.Workflows.WorkflowDefines workflows.
define: string -> ('Input -> Workflow<'Result>) -> WorkflowDefinition<'Input,'Result>A workflow named `name` whose instances run `body` on their input.
answer: StockAnswerReserve: string * string * int -> Task<StockAnswer>OutOfStockReservedFCQRS.Workflows.WorkflowStepFailedExceptionRaised in a workflow body when a step ended without a value. The body sees this exception both when the step fails and when a stored failure is replayed, never the original exception.
failed: WorkflowStepFailedExceptionStepName: stringThe step's name.
(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
// "order" is stored with every instance. It must not change.
public sealed class OrderWorkflow(
IWarehouse warehouse, ICarrier carrier, AggregateFactory accounts)
: Workflow<OrderRequest, OrderResult>("order")
{
// Up to five attempts, 200 ms apart, each allowed ten seconds.
private static readonly RetryPolicy ReserveRetry =
Retry.times(5, TimeSpan.FromSeconds(10))
.WithSchedule(RetrySchedules.Fixed(TimeSpan.FromMilliseconds(200)));
// Up to three attempts, each allowed ten seconds.
private static readonly RetryPolicy CallRetry =
Retry.times(3, TimeSpan.FromSeconds(10));
public override async WorkflowTask<OrderResult> Run(
WorkflowContext ctx, OrderRequest request)
{
try
{
// A failed attempt is not stored. FCQRS tries again until an
// attempt succeeds or the policy gives up.
var answer = await ctx.Activity("reserve-stock", ReserveRetry,
attempt => warehouse.Reserve(
attempt.IdempotencyKey, request.Item, request.Quantity));
// An answer is the step's result, whichever case it is. It is
// stored, and the policy does not retry it.
return answer switch
{
OutOfStock => Unfilled("out of stock"),
Reserved reserved =>
await Fulfil(ctx, request, reserved.Reservation),
};
}
// When a step's policy gives up, the step fails, and the body sees
// WorkflowStepFailedException. A warehouse that was busy at every
// attempt reserved nothing, so the order can end with a result. Any
// other failure is not caught.
catch (WorkflowStepFailedException failed)
when (failed.StepName == "reserve-stock")
{
return Unfilled("warehouse unavailable");
}
}
// The result of an order that reserved no stock.
private static OrderResult Unfilled(string status) =>
new(status, "", "", Guid.Empty, DateTime.MinValue);
// The rest of an order, once its stock is reserved.
private async WorkflowTask<OrderResult> Fulfil(
WorkflowContext ctx, OrderRequest request, string reservation)
{
// The body must give the same answers on every replay, so it
// reads the clock and makes GUIDs only through steps. FCQRS
// stores their values and replays them.
var placedAt = await ctx.Now();
var confirmation = await ctx.NewGuid();
OrderResult Finish(string status, string shipment) =>
new(status, reservation, shipment, confirmation, placedAt);
// Gives the stock back when the order does not ship.
Step<string> Release() =>
ctx.Activity("release-stock", ReserveRetry, attempt =>
warehouse.Release(attempt.IdempotencyKey, reservation));
// An order over 1000 waits for a person to approve it, for at
// most one day. With no answer by then, Received is false.
var total = request.UnitPrice * request.Quantity;
if (total > 1000m)
{
var answer = await ctx.WaitSignal<bool>(
"approval", TimeSpan.FromDays(1));
if (!(answer.Received && answer.Value))
{
await Release();
return Finish("not approved", "");
}
}
// The confirmation number identifies the payment, so a repeated
// debit is recognised as the same payment.
var payment = confirmation.ToString();
var reply = await ctx.Send<AccountCommand, AccountEvent>(
accounts, request.Customer, new Debit(payment, total));
if (reply is Rejected)
{
await Release();
return Finish("payment refused", "");
}
// Packing takes two seconds. The timer's due time is stored, so
// a restart does not start the wait again.
await ctx.Sleep(TimeSpan.FromSeconds(2));
var shipment = await ctx.Activity("ship", CallRetry,
attempt => carrier.Ship(
attempt.IdempotencyKey, reservation, request.Item));
return Finish("shipped", shipment);
}
}
OutOfStock reaches the body as a value, so the match (in C#, the switch) handles it. The
handler never sees it, because a handler sees only exceptions. The same holds for the Error that
ends the workflowResult block: no handler runs for it, so the code that receives it gives the
stock back.
workflowResult stores nothing of its own. The steps inside it are stored at the positions they
had in step 6, and a replay computes the Error again from their stored results. A call that
throws is still a failure: when the carrier throws at every attempt, ship fails and the block
ends with the exception, not with an Error.
The handler catches only a failure of reserve-stock, checked by StepName. The stand-in
warehouse refuses a call before it reserves anything, so after five refusals nothing has happened
and the order can end with a result, warehouse unavailable. A call that times out is different:
the warehouse may have reserved the stock, and the body would have to ask it or cancel the
reservation.
The exception carries Error.Kind, which tells why the step failed, for example Exhausted when
the attempts ran out, DeadlineExceeded when the step's deadline passed, or OutcomeUnknown when
a command got no reply. It does not carry the exception the call threw. The body sees only that
exception's type name and message, while a returned answer such as StockAnswer keeps its fields.
Return an expected failure as a value
compares the two.
A failure of any other step is not caught. It leaves the body, and the order faults: FCQRS
stores the failure as the order's end, and the order runs nothing more. A faulted order is final.
Nothing restarts it, and a start with the same ID stores nothing. To try the order again, start it
with a new ID. From FCQRS.Workflows 7.12.0, Resume also continues it at the failed step, and
WorkflowIdReuse.AfterFailure starts it again under the same ID.
Make the stand-ins fail
In Program.fs (Program.cs), replace the stand-in warehouse. It returns OutOfStock for a
gizmo and throws at every call for an anvil:
Shared setup
open System
open System.Collections.Generic
open System.Threading
open Microsoft.Data.Sqlite
open FCQRS.Common
open FCQRS.FSharp
open FCQRS.Workflows
open Account
open Order
// Unchanged from step 6.
let database = "orders.db"
let api = Unchecked.defaultof<IActor>
SystemCollectionsGenericThreadingMicrosoftDataSqliteFCQRSFCQRS.CommonContains common types like Events and Commands Functionality for Write Side.
FCQRS.FSharpIdiomatic-F# functional facade for FCQRS. Gives F# consumers the same one-call ergonomics the C# host-builder (HostExtensions.fs) gives C#, but with F# idioms: records-of-functions for the definitions, typed handles for the results, an explicit wiring pipeline, and plain helpers for saga side effects. It is a *pure addition* that wraps only the existing primitives (IActor.InitializeActor / SagaBuilder.initSimple / Projections.startTracked / InitializeSagaStarter / CreateCommandSubscription / Actor.api) and changes nothing in the C# interop layer or the core. open FCQRS.FSharp let api = Fcqrs.actor config loggerFactory (Some (Fcqrs.connect DBType.Sqlite conn)) "Cluster" let documents = Fcqrs.aggregate api { Name="Document"; Initial=...; Decide=...; Fold=... } let slugs = Fcqrs.aggregate api { Name="Slug"; Initial=...; Decide=...; Fold=... } let publication = Fcqrs.saga api (publicationDef documents.Factory slugs.Factory) Fcqrs.wireSagaStarters api [ publication ] let subs = Fcqrs.projection api (Projection.single 0 updateReadModel) // (Projection.multi when you must control which notifications publish) // send a command and await the matching aggregate reply: let! ev = documents.Send (Fcqrs.newCid()) (Fcqrs.aggregateId id) cmd (fun e -> ...)
WorkflowsFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.AccountFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Orderdatabase: stringapi: IActorMicrosoft.FSharp.Core.Operators.UncheckedThis module contains basic operations which do not apply runtime and/or static checks
defaultof: 'TGenerate a default value for any type. This is null for reference types, For structs, this is struct value where all fields have the default value. This function is unsafe in the sense that some F# values do not have proper null values.
FCQRS.Common.IActorDefines the core functionalities and context provided by the FCQRS environment to actors. This interface provides access to essential Akka.NET services and FCQRS initialization methods.
// A stand-in for the warehouse. It answers that it has no gizmos, and it is
// busy at every call for an anvil. For any other item it is busy for the
// first two calls with a key. It remembers keys, so a repeated call returns
// the first reservation.
type Warehouse() =
let calls = Dictionary<string, int>()
let reservations = Dictionary<string, string>()
let releases = HashSet<string>()
interface IWarehouse with
member _.Reserve(key, item, quantity) =
task {
if item = "gizmo" then
// Out of stock is an answer, so it is returned.
printfn $" warehouse has no gizmo (key {key})"
return OutOfStock
else
calls[key] <- (match calls.TryGetValue key with
| true, count -> count + 1
| _ -> 1)
if calls[key] <= 2 || item = "anvil" then
// Being busy is a failed call, so it is thrown.
printfn $" warehouse busy (key {key})"
invalidOp "The warehouse is busy"
if not (reservations.ContainsKey key) then
reservations[key] <- $"r-{reservations.Count + 1}"
let stock = $"{quantity} {item}"
printfn $" warehouse reserved {stock} (key {key})"
return Reserved reservations[key]
}
member _.Release(key, reservation) =
task {
if releases.Add key then
printfn $" warehouse released {reservation} (key {key})"
return reservation
}
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Warehousecalls: Dictionary<string,int>``.ctor``: unit -> unitInitializes a new instance of the class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
stringAn abbreviation for the CLI type . Basic Types
intAn abbreviation for the CLI type . Basic Types
reservations: Dictionary<string,string>releases: HashSet<string>``.ctor``: unit -> unitInitializes a new instance of the class that is empty and uses the default equality comparer for the set type.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.IWarehouse_: WarehouseReserve: Warehouse -> string * string * int -> Tasks.Task<StockAnswer>key: stringitem: stringquantity: inttask: TaskBuilderBuilds a task using computation expression syntax.
(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
OutOfStockItem: intGets or sets the value associated with the specified key. The key of the value to get or set. is . The property is retrieved and does not exist in the collection. The value associated with the specified key. If the specified key is not found, a get operation throws a , and a set operation creates a new element with the specified key.
TryGetValue: string * byref<int> -> boolGets the value associated with the specified key. The key of the value to get. When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the parameter. This parameter is passed uninitialized. is . if the contains an element with the specified key; otherwise, .
count: int(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World"
(<=): 'T -> 'T -> boolStructural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true
(||): bool -> bool -> boolBinary 'or'. When used as a binary operator the right hand value is evaluated only on demand The first value. The second value. The result of the operation.
invalidOp: string -> 'TThrow a exception The exception message. The result value. type FileReader(fileName: string) = let mutable isOpen = false member this.Open() = if isOpen then invalidOp "File is already open" // ... Here we may open the file ... isOpen <- true let reader = FileReader("journal.txt") reader.Open() // Executes fine reader.Open() // Throws System.InvalidOperationException: File is already open
``not``: bool -> boolNegate a logical value. Not True equals False and not False equals True The value to negate. The result of the negation. not (2 + 2 = 5) // Evaluates to true // not is a function that can be compose with other functions let fileDoesNotExist = System.IO.File.Exists >> not
ContainsKey: string -> boolDetermines whether the contains the specified key. The key to locate in the . is . if the contains an element with the specified key; otherwise, .
Item: stringGets or sets the value associated with the specified key. The key of the value to get or set. is . The property is retrieved and does not exist in the collection. The value associated with the specified key. If the specified key is not found, a get operation throws a , and a set operation creates a new element with the specified key.
stock: stringReservedRelease: Warehouse -> string * string -> Tasks.Task<string>reservation: stringAdd: string -> boolAdds the specified element to a set. The element to add to the set. if the element is added to the object; if the element is already present.
// A stand-in for the warehouse. It answers that it has no gizmos, and it is
// busy at every call for an anvil. For any other item it is busy for the
// first two calls with a key. It remembers keys, so a repeated call returns
// the first reservation.
public sealed class Warehouse : IWarehouse
{
private readonly Dictionary<string, int> calls = new();
private readonly Dictionary<string, string> reservations = new();
private readonly HashSet<string> releases = new();
public Task<StockAnswer> Reserve(string key, string item, int quantity)
{
if (item == "gizmo")
{
// Out of stock is an answer, so it is returned.
Console.WriteLine($" warehouse has no gizmo (key {key})");
return Task.FromResult<StockAnswer>(new OutOfStock());
}
calls[key] = calls.GetValueOrDefault(key) + 1;
if (calls[key] <= 2 || item == "anvil")
{
// Being busy is a failed call, so it is thrown.
Console.WriteLine($" warehouse busy (key {key})");
throw new InvalidOperationException("The warehouse is busy");
}
if (!reservations.ContainsKey(key))
{
reservations[key] = $"r-{reservations.Count + 1}";
Console.WriteLine(
$" warehouse reserved {quantity} {item} (key {key})");
}
return Task.FromResult<StockAnswer>(new Reserved(reservations[key]));
}
public Task<string> Release(string key, string reservation)
{
if (releases.Add(key))
Console.WriteLine(
$" warehouse released {reservation} (key {key})");
return Task.FromResult(reservation);
}
}
Replace the stand-in carrier. It does not take crates:
// A stand-in for the carrier. It does not take crates. A call takes two
// seconds. With `crash`, the process stops after the carrier ships and
// before FCQRS stores the result.
type Carrier(crash: bool) =
let shipments = Dictionary<string, string>()
interface ICarrier with
member _.Ship(key, reservation, item) =
task {
if item = "crate" then
printfn $" carrier does not take crates (key {key})"
invalidOp "The carrier does not take crates"
Thread.Sleep 2000
if not (shipments.ContainsKey key) then
shipments[key] <- $"s-{shipments.Count + 1}"
printfn $" carrier shipped {reservation} (key {key})"
if crash then
printfn " the process stops before this step is stored"
exit 1
return shipments[key]
}
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Carriercrash: boolboolAn abbreviation for the CLI type . Basic Types
shipments: Dictionary<string,string>``.ctor``: unit -> unitInitializes a new instance of the class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
stringAn abbreviation for the CLI type . Basic Types
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.ICarrier_: CarrierShip: Carrier -> string * string * string -> Tasks.Task<string>key: stringreservation: stringitem: stringtask: TaskBuilderBuilds a task using computation expression syntax.
(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
invalidOp: string -> 'TThrow a exception The exception message. The result value. type FileReader(fileName: string) = let mutable isOpen = false member this.Open() = if isOpen then invalidOp "File is already open" // ... Here we may open the file ... isOpen <- true let reader = FileReader("journal.txt") reader.Open() // Executes fine reader.Open() // Throws System.InvalidOperationException: File is already open
System.Threading.ThreadCreates and controls a thread, sets its priority, and gets its status.
Sleep: int -> unitSuspends the current thread for the specified number of milliseconds. The number of milliseconds for which the thread is suspended. If the value of the argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended. The time-out value is negative and is not equal to .
``not``: bool -> boolNegate a logical value. Not True equals False and not False equals True The value to negate. The result of the negation. not (2 + 2 = 5) // Evaluates to true // not is a function that can be compose with other functions let fileDoesNotExist = System.IO.File.Exists >> not
ContainsKey: string -> boolDetermines whether the contains the specified key. The key to locate in the . is . if the contains an element with the specified key; otherwise, .
Item: stringGets or sets the value associated with the specified key. The key of the value to get or set. is . The property is retrieved and does not exist in the collection. The value associated with the specified key. If the specified key is not found, a get operation throws a , and a set operation creates a new element with the specified key.
exit: int -> 'TExit the current hardware isolated process, if security settings permit, otherwise raise an exception. Calls . The exit code to use. Never returns. [<EntryPoint>] let main argv = if argv.Length = 0 then eprintfn "You must provide arguments" exit(-1) // Causes program to quit with an error code printfn "Argument count: %i" argv.Length 0
// A stand-in for the carrier. It does not take crates. A call takes two
// seconds. With `crash`, the process stops after the carrier ships and
// before FCQRS stores the result.
public sealed class Carrier(bool crash) : ICarrier
{
private readonly Dictionary<string, string> shipments = new();
public Task<string> Ship(string key, string reservation, string item)
{
if (item == "crate")
{
Console.WriteLine($" carrier does not take crates (key {key})");
throw new InvalidOperationException(
"The carrier does not take crates");
}
Thread.Sleep(2000);
if (!shipments.ContainsKey(key))
{
shipments[key] = $"s-{shipments.Count + 1}";
Console.WriteLine($" carrier shipped {reservation} (key {key})");
}
if (crash)
{
Console.WriteLine(" the process stops before this step is stored");
Environment.Exit(1);
}
return Task.FromResult(shipments[key]);
}
}
Replace the code that starts the orders. place takes the item, and reports a faulted order. The
program places a gizmo, an anvil, and a crate, then starts o-8, a large order, and leaves it
waiting for an approval it never sends:
Shared setup
let accounts =
Unchecked.defaultof<AggregateHandle<AccountCommand, AccountEvent>>
let orders = Unchecked.defaultof<WorkflowHandle<OrderRequest, OrderResult>>
accounts: AggregateHandle<AccountCommand,AccountEvent>Microsoft.FSharp.Core.Operators.UncheckedThis module contains basic operations which do not apply runtime and/or static checks
defaultof: 'TGenerate a default value for any type. This is null for reference types, For structs, this is struct value where all fields have the default value. This function is unsafe in the sense that some F# values do not have proper null values.
FCQRS.FSharp.AggregateHandle`2What you get back after registering an aggregate.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountCommandFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Account.AccountEventorders: WorkflowHandle<OrderRequest,OrderResult>FCQRS.Workflows.WorkflowHandle`2Starts and queries the instances of a registered workflow.
Fcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.OrderRequestFcqrs_350-workflow-tutorial_007-when-a-step-fails.md_page.Order.OrderResult// Put money in a customer's account.
let deposit customer amount =
accounts.Send
(Fcqrs.newCid ()) (Fcqrs.aggregateId customer) (Deposit amount)
(fun _ -> true)
|> Async.RunSynchronously
|> ignore
printfn $"Deposited {amount} to {customer}"
// Start an order. A start with an ID that is already in the journal stores
// nothing and returns the order's status.
let start id request =
match orders.Start id request |> Async.RunSynchronously with
| StartResult.Started -> printfn $"Started {id}"
| StartResult.AlreadyStarted status ->
printfn $"{id} is already started ({status})"
// Start an order, send it an approval if given one, and wait for its end.
let place id customer item quantity approval =
let request = {
Customer = customer
Item = item
Quantity = quantity
UnitPrice = 40m
}
start id request
match approval with
| Some approve ->
Workflows.signal orders id "approval" approve |> Async.RunSynchronously
| None -> ()
let outcome =
orders.Result id (TimeSpan.FromSeconds 30.0) |> Async.RunSynchronously
match outcome with
| WorkflowOutcome.Finished result when result.Status = "shipped" ->
printfn $"{id} finished: shipped as {result.Shipment}"
| WorkflowOutcome.Finished result ->
printfn $"{id} finished: {result.Status}"
| WorkflowOutcome.Faulted error -> printfn $"{id} faulted: {error.Message}"
| other -> printfn $"{id} ended: {other}"
deposit "ada" 1500m
deposit "bob" 50m
// The warehouse has no gizmos.
place "o-5" "ada" "gizmo" 1 None
// The warehouse is busy at every call for an anvil.
place "o-6" "ada" "anvil" 1 None
// The carrier does not take crates.
place "o-7" "ada" "crate" 1 None
// o-8 costs 1200 and waits for an approval that this program never sends.
// Step 8 finds it still waiting.
let big = { Customer = "ada"; Item = "widget"; Quantity = 30; UnitPrice = 40m }
start "o-8" big
let rec waitForApproval () =
match orders.Status "o-8" |> Async.RunSynchronously with
| WorkflowStatus.Running steps as status
when steps |> List.exists (fun step -> step.EndsWith " approval") ->
printfn $"o-8 status: {status}"
| _ ->
Thread.Sleep 50
waitForApproval ()
waitForApproval ()
deposit: string -> decimal -> unitcustomer: stringamount: decimalaccounts: AggregateHandle<AccountCommand,AccountEvent>Send: FCQRS.Model.Data.CID -> FCQRS.Model.Data.AggregateId -> 'Command -> ('Event -> bool) -> Async<Event<'Event>>Send a command and await the first matching aggregate event. Fails with SagaAlreadyStartedException, with nothing stored, when the command would start a saga that its correlation ID already started on this aggregate.
FCQRS.FSharp.FcqrsnewCid: unit -> FCQRS.Model.Data.CIDA fresh correlation id (UUID v7).
aggregateId: string -> FCQRS.Model.Data.AggregateIdAn aggregate id from a string (e.g. a document/user key). Any non-blank id works: the shard names entity actors Uri.EscapeDataString(entityId), so characters Akka actor names would reject directly (spaces, %) are escaped before they reach an actor path.
Deposit(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Microsoft.FSharp.Control.FSharpAsyncHolds static members for creating and manipulating asynchronous computations. See also F# Language Guide - Async Workflows. Async Programming
RunSynchronously: Async<'T> * int option * CancellationToken option -> 'TRuns the asynchronous computation and await its result. If an exception occurs in the asynchronous computation then an exception is re-raised by this function. If no cancellation token is provided then the default cancellation token is used. The computation is started on the current thread if is null, has of true, and no timeout is specified. Otherwise the computation is started by queueing a new work item in the thread pool, and the current thread is blocked awaiting the completion of the computation. The timeout parameter is given in milliseconds. A value of -1 is equivalent to . The computation to run. The amount of time in milliseconds to wait for the result of the computation before raising a . If no value is provided for timeout then a default of -1 is used to correspond to . The cancellation token to be associated with the computation. If one is not supplied, the default cancellation token is used. The result of the computation. Starting Async Computations printfn "A" let result = async { printfn "B" do! Async.Sleep(1000) printfn "C" 17 } |> Async.RunSynchronously printfn "D" Prints "A", "B" immediately, then "C", "D" in 1 second. result is set to 17.
ignore: 'T -> unitIgnore the passed value. This is often used to throw away results of a computation. The value to ignore. ignore 55555 // Evaluates to ()
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
start: string -> OrderRequest -> unitid: stringrequest: OrderRequestorders: WorkflowHandle<OrderRequest,OrderResult>Start: string -> 'Input -> Async<StartResult>Starts the workflow with this ID. Returns once the start is stored. A second start with the same ID stores nothing and reports the existing instance, also when it has ended.
FCQRS.Workflows.StartResultThe answer to a start request.
StartedThis request started the workflow, or a new run of it.
AlreadyStartedA workflow with this ID exists and the start's reuse policy keeps it. Nothing was stored.
status: WorkflowStatusplace: string -> string -> string -> int -> 'a option -> unititem: stringquantity: intapproval: 'a optionCustomer: stringItem: stringQuantity: intUnitPrice: decimalSomeThe representation of "Value of type 'T" The input value. An option representing the value.
approve: 'aFCQRS.Workflows.WorkflowsRegisters workflows with an actor system.
signal: WorkflowHandle<'Input,'Result> -> string -> string -> 'Signal -> Async<unit>Stores the signal `name` with a typed payload for the instance `id`.
NoneThe representation of "No value"
outcome: WorkflowOutcome<OrderResult>Result: string -> TimeSpan -> Async<WorkflowOutcome<'Result>>Waits up to the given time for the instance to end. The wait is in memory: the workflow continues when the caller stops waiting. Raises `TimeoutException` when the time passes, and `InvalidOperationException` when no workflow with this ID was started.
System.TimeSpanRepresents a time interval.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. is less than TimeSpan.MinValue or greater than TimeSpan.MaxValue. -or- is . -or- is . is equal to . An object that represents .
FCQRS.Workflows.WorkflowOutcome`1How a workflow ended.
FinishedThe body returned this value.
result: OrderResultStatus: string(=): 'T -> 'T -> boolStructural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false
FaultedThe body threw an exception it did not handle.
error: StepErrorother: WorkflowOutcome<OrderResult>big: OrderRequestwaitForApproval: unit -> unitStatus: string -> Async<WorkflowStatus>Where the instance is.
FCQRS.Workflows.WorkflowStatusWhere a workflow instance is.
RunningThe body is waiting on these steps, given as "path name".
steps: string listMicrosoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
exists: ('T -> bool) -> 'T list -> boolTests if any element of the list satisfies the given predicate. The predicate is applied to the elements of the input list. If any application returns true then the overall result is true and no further elements are tested. Otherwise, false is returned. This is an O(n) operation in the worst case, where n is the length of the list. The function to test the input elements. The input list. True if any element satisfies the predicate. let input = [1, "Kirk"; 2, "Spock"; 3, "Kenobi"] input |> List.exists (fun x -> x = (3, "Kenobi")) // evaluates true input |> List.exists (fun (n, name) -> n > 5) // evaluates false
step: stringEndsWith: string -> boolSystem.Threading.ThreadCreates and controls a thread, sets its priority, and gets its status.
Sleep: int -> unitSuspends the current thread for the specified number of milliseconds. The number of milliseconds for which the thread is suspended. If the value of the argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended. The time-out value is negative and is not equal to .
// Put money in a customer's account.
async Task Deposit(string customer, decimal amount)
{
await accounts.Handler(_ => true, Values.NewCID(),
Values.CreateAggregateId(customer), new Deposit(amount));
Console.WriteLine($"Deposited {amount} to {customer}");
}
// Start an order. A start with an ID that is already in the journal stores
// nothing and returns false.
async Task Start(string id, OrderRequest request)
{
if (await orders.StartAsync(id, request))
Console.WriteLine($"Started {id}");
else
Console.WriteLine(
$"{id} is already started ({await orders.StatusAsync(id)})");
}
// Start an order, send it an approval if given one, and wait for its end.
async Task Place(
string id, string customer, string item, int quantity, bool? approval)
{
await Start(id, new OrderRequest(customer, item, quantity, 40m));
if (approval is bool approve)
await orders.SignalAsync(id, "approval", approve);
try
{
var result = await orders.ResultAsync(id, TimeSpan.FromSeconds(30));
Console.WriteLine(result.Status == "shipped"
? $"{id} finished: shipped as {result.Shipment}"
: $"{id} finished: {result.Status}");
}
catch (WorkflowFaultedException faulted)
{
Console.WriteLine($"{id} faulted: {faulted.Error.Message}");
}
}
await Deposit("ada", 1500m);
await Deposit("bob", 50m);
// The warehouse has no gizmos.
await Place("o-5", "ada", "gizmo", 1, null);
// The warehouse is busy at every call for an anvil.
await Place("o-6", "ada", "anvil", 1, null);
// The carrier does not take crates.
await Place("o-7", "ada", "crate", 1, null);
// o-8 costs 1200 and waits for an approval that this program never sends.
// Step 8 finds it still waiting.
await Start("o-8", new OrderRequest("ada", "widget", 30, 40m));
while (true)
{
var status = await orders.StatusAsync("o-8");
if (status is WorkflowStatus.Running running
&& running.pending.Any(step => step.EndsWith(" approval")))
{
Console.WriteLine($"o-8 status: {status}");
break;
}
await Task.Delay(50);
}
Replace the code that prints the journal. It now takes an order's ID and prints o-7's:
// Applications do not read this table. This program reads it only to show
// what FCQRS stored for an order.
let printJournal id =
use connection = new SqliteConnection($"Data Source={database}")
connection.Open()
let command = connection.CreateCommand()
command.CommandText <-
"SELECT sequence_number, manifest FROM journal
WHERE persistence_id = $id
ORDER BY sequence_number"
let persistenceId = $"order/default-shard/{id}"
command.Parameters.AddWithValue("$id", persistenceId) |> ignore
use rows = command.ExecuteReader()
printfn $"Journal of order/default-shard/{id}:"
while rows.Read() do
// The manifest names the stored type, for example
// "FCQRS.Workflows.WorkflowRecord+Started, FCQRS.Workflows".
let manifest = rows.GetString 1
let record = manifest.Split(',').[0].Split('+').[1]
let number = rows.GetInt64 0
printfn $" {number} {record}"
printJournal "o-7"
api.Stop().Wait()
printJournal: 'a -> unitid: 'aconnection: SqliteConnectionMicrosoft.Data.Sqlite.SqliteConnectionRepresents a connection to a SQLite database. Connection Strings Async Limitations
Open: unit -> unitOpens a connection to the database using the value of . If Mode=ReadWriteCreate is used (the default) the file is created, if it doesn't already exist. A SQLite error occurs while opening the connection.
command: SqliteCommandCreateCommand: unit -> SqliteCommandCreates a new command associated with the connection. The new command. The command's property will also be set to the current transaction.
CommandText: stringGets or sets the SQL to execute against the database. The SQL to execute against the database. Batching
persistenceId: stringAddWithValue: string * obj -> SqliteParameterAdds a parameter to the collection. The name of the parameter. The value of the parameter. Can be null. The parameter that was added. Parameters Data Types
Parameters: SqliteParameterCollectionGets the collection of parameters used by the command. The collection of parameters used by the command. Parameters
(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
ignore: 'T -> unitIgnore the passed value. This is often used to throw away results of a computation. The value to ignore. ignore 55555 // Evaluates to ()
rows: SqliteDataReaderExecuteReader: unit -> SqliteDataReaderExecutes the against the database and returns a data reader. The data reader. A SQLite error occurs during execution. Database Errors Batching
printfn: Printf.TextWriterFormat<'T> -> 'TPrint to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples.
Read: unit -> boolAdvances to the next row in the result set. if there are more rows; otherwise, .
manifest: stringGetString: int -> stringGets the value of the specified column as a . The zero-based column ordinal. The value of the column.
record: stringSplit: char * StringSplitOptions -> string arraynumber: int64GetInt64: int -> int64Gets the value of the specified column as a . The zero-based column ordinal. The value of the column.
api: IActorStop: unit -> Tasks.TaskStops the actor system gracefully.
Wait: unit -> unitWaits for the to complete execution. The has been disposed. The task was canceled. The collection contains a object. -or- An exception was thrown during the execution of the task. The collection contains information about the exception or exceptions.
// Applications do not read this table. This program reads it only to show
// what FCQRS stored for an order.
void PrintJournal(string id)
{
using var connection = new SqliteConnection($"Data Source={database}");
connection.Open();
var command = connection.CreateCommand();
command.CommandText = """
SELECT sequence_number, manifest FROM journal
WHERE persistence_id = $id
ORDER BY sequence_number
""";
command.Parameters.AddWithValue("$id", $"order/default-shard/{id}");
using var rows = command.ExecuteReader();
Console.WriteLine($"Journal of order/default-shard/{id}:");
while (rows.Read())
{
// The manifest names the stored type, for example
// "FCQRS.Workflows.WorkflowRecord+Started, FCQRS.Workflows".
var record = rows.GetString(1).Split(',')[0].Split('+')[1];
Console.WriteLine($" {rows.GetInt64(0)} {record}");
}
}
PrintJournal("o-7");
await actor.Stop();
Run it
Delete bin/Debug/net11.0/orders.db, then run dotnet run. Keep the database afterwards: step 8
continues from it.
Deposited 1500 to ada
Deposited 50 to bob
Started o-5
warehouse has no gizmo (key order/o-5/0)
o-5 finished: out of stock
Started o-6
warehouse busy (key order/o-6/0)
warehouse busy (key order/o-6/0)
warehouse busy (key order/o-6/0)
warehouse busy (key order/o-6/0)
warehouse busy (key order/o-6/0)
o-6 finished: warehouse unavailable
Started o-7
warehouse busy (key order/o-7/0)
warehouse busy (key order/o-7/0)
warehouse reserved 1 crate (key order/o-7/0)
carrier does not take crates (key order/o-7/5)
carrier does not take crates (key order/o-7/5)
carrier does not take crates (key order/o-7/5)
o-7 faulted: The carrier does not take crates
Started o-8
warehouse busy (key order/o-8/0)
warehouse busy (key order/o-8/0)
warehouse reserved 30 widget (key order/o-8/0)
o-8 status: Running ["3 approval"]
Journal of order/default-shard/o-7:
1 Started
2 StepScheduled
3 StepCompleted
4 StepCompleted
5 StepCompleted
6 StepScheduled
7 StepCompleted
8 StepScheduled
9 StepCompleted
10 StepScheduled
11 StepFailed
12 Faulted
o-5: the warehouse was called once.reserve-stockstored its answer, and the body returned the resultout of stock.o-6:reserve-stockmade its five attempts and failed. The body caught the failure and returned the resultwarehouse unavailable.o-7:shipmade its three attempts and failed. Nothing caught it, so the order faulted. In F#,ResultreturnsWorkflowOutcome.Faultedwith the stored error. In C#,ResultAsyncthrowsWorkflowFaultedException.o-8is waiting for its approval at position 3 when the program stops.
What a faulted order leaves behind
o-7's journal shows what happened before the failure. Records 6 and 7 are the payment: Ada's
account was charged. Records 8 and 9 are the packing timer. Records 10 and 11 are ship, which
began and failed. Record 12 ends the order.
So the customer paid, the stock is reserved, and nothing will ship. FCQRS does not undo the earlier
steps of a faulted order, because it cannot know what undoing them means. If a failure leaves work
to undo, the body must catch it and run the undo steps, as release-stock does after a refused
payment. A failure that nobody expected is for a person to look at: a faulted order and its
journal record what it did.
Next
Step 8: Add a step changes the workflow while o-8 is still waiting.