Start a workflow from an aggregate event
Most workflows start from a request: the application calls Start with an ID it chose, as
Transfer money does. Some work follows from an event that no single
request asks for, such as welcoming the owner of every account that opens, whichever code path
opened it. This recipe starts a Welcome workflow for each Opened event an account stores, from a
projection.
The complete programs are in samples/start-from-an-event/fsharp and
samples/start-from-an-event/csharp.
The account and the workflow
The account stores Opened once, and rejects a second Open without storing anything:
Shared setup
open System
open System.Threading.Tasks
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.Logging
open FCQRS.Actor
open FCQRS.Common
open FCQRS.FSharp
open FCQRS.Workflows
SystemThreadingTasksMicrosoftExtensionsConfigurationLoggingFCQRSFCQRS.ActorFCQRS.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 -> ...)
Workflows// An account that can only be opened. Opening it stores Opened, the event
// that starts a welcome.
type AccountCommand = Open of owner: string
type AccountEvent =
| Opened of owner: string
// A reply only: it is never stored.
| Rejected of reason: string
type AccountState = { Owner: string option }
let initial = { Owner = None }
let decide (command: Command<AccountCommand>) (state: AccountState) =
match command.CommandDetails, state.Owner with
| Open _, Some _ -> DeferEvent(Rejected "The account is already open")
| Open owner, None -> PersistEvent(Opened owner)
let fold (event: Event<AccountEvent>) (state: AccountState) =
match event.EventDetails with
| Opened owner -> { state with Owner = Some owner }
| Rejected _ -> state
Fcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.AccountCommandOpenowner: stringstringAn abbreviation for the CLI type . Basic Types
Fcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.AccountEventOpenedRejectedreason: stringFcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.AccountStateOwner: string optionoptionThe type of optional values. When used from other CLI languages the empty option is the null value. Use the constructors Some and None to create values of this type. Use the values in the Option module to manipulate values of this type, or pattern match against the values directly. 'None' values will appear as the value null to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of null as a value representation. Options
initial: AccountStateNoneThe representation of "No value"
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.
SomeThe representation of "Value of type 'T" The input value. An option representing the value.
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.
PersistEventPersist the event to the journal. The actor's state will be updated using the event handler *after* persistence succeeds.
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.
// An account that can only be opened. Opening it stores Opened, the event
// that starts a welcome.
public sealed record Open(string Owner);
// The case names are stored with each event, so they must not change.
[JsonDerivedType(typeof(Opened), "Opened")]
[JsonDerivedType(typeof(Rejected), "Rejected")]
public abstract record AccountEvent;
public sealed record Opened(string Owner) : AccountEvent;
// A reply only: it is never stored.
public sealed record Rejected(string Reason) : AccountEvent;
public sealed record AccountState(string? Owner);
public sealed class Account : Aggregate<AccountState, Open, AccountEvent>
{
public override string EntityName => "Account";
public override AccountState InitialState => new((string?)null);
public override EventAction<AccountEvent> HandleCommand(
Command<Open> command, AccountState state) =>
state.Owner is null
? EventActions.Persist<AccountEvent>(
new Opened(command.CommandDetails.Owner))
: EventActions.Defer<AccountEvent>(
new Rejected("The account is already open"));
public override AccountState ApplyEvent(
Event<AccountEvent> stored, AccountState state) =>
stored.EventDetails is Opened opened ? new(opened.Owner) : state;
}
The workflow sends one welcome through an external service, with the step's idempotency key:
// The service that sends a welcome. A call gets a key that is the same for
// every attempt of one step, so the service can recognise a repeat.
type IWelcomes =
abstract Send: key: string * owner: string -> Task<bool>
let private policy = Retry.times 3 (TimeSpan.FromSeconds 10.)
// Welcomes a new account's owner. The input is the owner's name.
let definition (welcomes: IWelcomes) =
Workflow.define "Welcome" (fun (owner: string) ->
workflow {
let! _ =
activity "send-welcome" policy (fun attempt ->
welcomes.Send(attempt.IdempotencyKey, owner))
return "welcomed"
})
Fcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.IWelcomesSend: IWelcomes -> string * string -> Task<bool>keystringAn abbreviation for the CLI type . Basic Types
ownerSystem.Threading.Tasks.Task`1Represents an asynchronous operation that can return a value. The type of the result produced by this .
boolAn abbreviation for the CLI type . Basic Types
policy: 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`.
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 .
definition: IWelcomes -> WorkflowDefinition<string,string>welcomes: IWelcomesFCQRS.Workflows.WorkflowDefines workflows.
define: string -> ('Input -> Workflow<'Result>) -> WorkflowDefinition<'Input,'Result>A workflow named `name` whose instances run `body` on their input.
owner: stringworkflow: WorkflowBuilderBuilds a workflow: `workflow { let! x = activity ... }`.
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.
attempt: AttemptContextSend: string * string -> Task<bool>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.
// The service that sends a welcome. A call gets a key that is the same for
// every attempt of one step, so the service can recognise a repeat.
public interface IWelcomes
{
Task<bool> Send(string key, string owner);
}
// Welcomes a new account's owner. The input is the owner's name.
public sealed class WelcomeWorkflow(IWelcomes welcomes)
: Workflow<string, string>("Welcome")
{
private static readonly RetryPolicy Policy =
Retry.times(3, TimeSpan.FromSeconds(10));
public override async WorkflowTask<string> Run(
WorkflowContext ctx, string owner)
{
await ctx.Activity("send-welcome", Policy,
attempt => welcomes.Send(attempt.IdempotencyKey, owner));
return "welcomed";
}
}
Start the workflow from a projection
Shared setup
let logging = LoggerFactory.Create(fun _ -> ())
let configuration = ConfigurationBuilder().Build()
let connection = Fcqrs.connect DBType.Sqlite "Data Source=accounts.db"
let api = Fcqrs.actor configuration logging (Some connection) "accounts"
let welcomeService =
{ new IWelcomes with
member _.Send(_, _) = Task.FromResult true }
let welcomes = Workflows.register api (definition welcomeService)
logging: ILoggerFactoryMicrosoft.Extensions.Logging.LoggerFactoryProduces instances of classes based on the given providers.
Create: Action<ILoggingBuilder> -> ILoggerFactoryCreates new instance of configured using provided delegate. A delegate to configure the . The that was created.
configuration: IConfigurationRoot``.ctor``: unit -> unitBuild: unit -> IConfigurationRootBuilds an with keys and values from the set of providers registered in . An with keys and values from the registered providers.
connection: ConnectionFCQRS.FSharp.Fcqrsconnect: DBType -> string -> ConnectionBuild a SQLite/etc. Connection from a raw connection string of any length.
FCQRS.Actor.DBTypeRepresents the type of database connection
SqliteSQLite using Microsoft.Data.Sqlite provider
api: IActoractor: IConfiguration -> ILoggerFactory -> Connection option -> string -> IActorCreate the actor system from plain values (cluster name as a string).
SomeThe representation of "Value of type 'T" The input value. An option representing the value.
welcomeService: IWelcomesFcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.IWelcomes_: IWelcomesSend: string * string -> Task<bool>System.Threading.Tasks.TaskRepresents an asynchronous operation.
FromResult: 'TResult -> Task<'TResult>Creates a that's completed successfully with the specified result. The result to store into the completed task. The type of the result returned by the task. The successfully completed task.
welcomes: WorkflowHandle<string,string>FCQRS.Workflows.WorkflowsRegisters workflows with an actor system.
register: IActor -> WorkflowDefinition<'Input,'Result> -> WorkflowHandle<'Input,'Result>Registers the workflow and returns its handle. Instances that were running when the process last stopped resume as soon as this is called.
definition: IWelcomes -> WorkflowDefinition<string,string>// Starts a welcome for each stored Opened event. The workflow ID comes from
// the event, so a start for an event the projection hands over again stores
// nothing. The projection stores how far it has read after the handler
// returns, so a crash before that hands the event over again.
let startWelcome (event: obj) =
match event with
| :? Event<AccountEvent> as stored ->
match stored.EventDetails with
| Opened owner ->
let id = $"welcome-{stored.Sender.Value}"
welcomes.Start id owner |> Async.RunSynchronously |> ignore
| _ -> ()
| _ -> ()
let starter =
Projection.single (Named "welcome-starter") startWelcome
|> Projection.ofEntities [ "Account" ]
|> Fcqrs.projection api
startWelcome: obj -> unitevent: objobjAn abbreviation for the CLI type . Basic Types
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>
Fcqrs_550-how-to_013-start-a-workflow-from-an-event.md_page.AccountEventstored: Event<AccountEvent>EventDetails: 'EventDetailsThe specific details or payload of the event.
Openedowner: stringid: stringwelcomes: WorkflowHandle<string,string>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.
(|>): '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 * Threading.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 ()
starter: FCQRS.Projections.IProjectionFCQRS.FSharp.ProjectionModuleConstructors for the projection-handler shapes.
single: ProjectionProgress -> (obj -> unit) -> ProjectionSingle-event handler: just update the read model (returns unit); each aggregate event is then published to subscribers as-is. The common case when every event is worth notifying.
NamedStored in the journal database under this name: the projection resumes where it stopped. For a read model that outlives the process. A new name reads the whole journal once. The position is stored after the handler returns, outside the handler, so the handler can wait for a journal write such as a workflow start. A name that starts with `fcqrs-` is reserved for FCQRS's own projections, and `Fcqrs.projection` raises `ArgumentException` for it.
ofEntities: string list -> Projection -> ProjectionReads only the events of the named entities: an aggregate's, saga's, or workflow's name, as registered. A name selects the persistence IDs that start with it, escaped as Akka escapes a sharding region's name (Uri.EscapeDataString), and "/". The journal queries select those rows in SQL, so other entities' events are not fetched or deserialized. On SQLite and SQL Server the full scan reads only the names' range of the journal's persistence-ID index, and the queries bounded by a journal number read every row above it; PostgreSQL reads other entities' rows in every query. A pass reads each persistence ID's events with a query of its own. A pass hands the named entities' events to the handler in journal order, as without a filter. An empty list reads every entity.
FCQRS.FSharp.Fcqrsprojection: IActor -> Projection -> FCQRS.Projections.IProjectionRegister the read-model projection and return the subscription stream. Starts a projection. It follows each aggregate's and saga's own sequence numbers, so it never skips a stored event. Each pass hands the events it found to the handler in journal order, so each aggregate's events arrive in sequence order; on SQLite, events of different aggregates arrive in the order they were written, and on PostgreSQL, SQL Server, and Oracle an event that commits late arrives in a later pass. With `Entities` (see Projection.ofEntities), it reads only those entities' events. With `Named` progress, a handler can see an event again after a crash. A handler that throws terminates the process. Requires a SQLite, PostgreSQL, SQL Server, or Oracle journal; an Akka event adapter must turn each journal row into one event.
api: IActor// Starts a welcome for each stored Opened event. The workflow ID comes from
// the event, so a start for an event the projection hands over again stores
// nothing. The projection stores how far it has read after the handler
// returns, so a crash before that hands the event over again.
builder.Services.AddFcqrs($"Data Source={database}", "accounts")
.AddAggregate<Account>()
.AddProjection(services =>
{
var welcomes = services
.GetRequiredService<IWorkflowClient<string, string>>();
return (Action<object>)(message =>
{
if (message is Event<AccountEvent>
{
EventDetails: Opened opened, Sender: { } sender
})
{
var id = $"welcome-{sender.Value}";
welcomes.StartAsync(id, opened.Owner).GetAwaiter().GetResult();
}
});
}, name: "welcome-starter", entities: ["Account"]);
The projection reads the account's journal and calls Start for each Opened. Three choices make
every stored event start its workflow once:
- The workflow ID comes from the event.
welcome-alicenames the account that storedOpened. A second start with the same ID stores nothing, so a handler that runs twice for one event starts one workflow. For an event that an aggregate can store more than once, add its version to the ID. - The projection stores its progress. With a name, it keeps how far it has read in the journal's database and stores the position after the handler returns. A process that stops before that hands the same event to the handler again after the restart, and the start stores nothing the second time. A projection without a name rereads the whole journal at every start.
- The handler waits for the start.
Startreturns once the workflow has stored its start, so the projection moves past an event only after its workflow exists.
Only stored events reach a projection. A rejected Open is a reply, not an event, so it starts
nothing.
Run it
From the repository root:
dotnet run --project samples/start-from-an-event/fsharp
dotnet run --project samples/start-from-an-event/csharp
The first run prints:
Opened for Alice (version 1, stored)
Sending a welcome to Alice
welcome-alice: welcomed
A second run finds Alice's account open, and the projection resumes after the event it handled, so no welcome is sent again:
Rejected: The account is already open (version 1, not stored)
welcome-alice: welcomed
What the projection does not do
- It starts the workflow after the event, not with it. A projection follows the journal, so the start comes one poll interval, a second by default, after the event is stored. A workflow that must exist before anything else happens belongs at the request: start it from the code that sends the command.
- A start that fails stops the process. A handler that raises terminates the process, as
Add a projection describes, and the restarted
projection hands the same event over again.
StartraisesTimeoutExceptionwhen the workflow does not answer within 30 seconds. - A transactional projection cannot start workflows on SQLite. Its handler runs while the transaction holds the database's single writer lock, and the workflow's start is a journal write that waits for that lock. Use a named projection, as here, which stores its position after the handler returns.
- It does not replace the workflow's idempotency. The welcome service still sees each attempt's key, and must recognise a repeat: the activity runs at least once.
Next: Run scheduled jobs starts workflows nightly, weekly, or at an interval.