// thinkbeforecoding

SimpleCQRS the F# version

Here it is ! As promised after greg’s talk at dddx (you can already see all the presentations online !), a F# version of SimpleCQRS, a simple, quick EventSourcing + CQRS sample to see it in action.

Why rewrite it in F# ?

This is not just a simple copy of the C# version. The point was first to write it in a functional language, because event sourcing is inherently functional.

In C#, an aggregate method looks like this :

public void CheckIn(int count)
{
  if(count <= 0)
    throw new InvalidOperationException(
      &quot;must have a count greater than 0 to add to inventory&quot;);
    ApplyChange(new ItemsCheckedInToInventory(_id, count));
}

The ApplyChange method is defined in the AggregateRoot base class.

It dispatches the event to a state denormalizer and add the Event to uncommitted changes.

Here is a denormalizer to apply a state change following an event :

private void Apply(InventoryItemDeactivated e)
{
  _activated = false;
}

All this is fine, but why should the aggregate be mutable when the event stream is highly a append only store of immutable events.

Watch greg’s talk carefully, both methods can be transformed to an immutable equivalent easily.

First the goal of the public method is to determine which event to raise based on command parameters and current state. The CheckIn method can be defined by the following method signature:

int -> State -> Event or Func<int,State,Event>

Instead of calling an Apply change internally, the method simply returns an event :

let checkIn count s =
    if count <= 0 then
        raise (InvalidOperationException "must have a count greater than 0 to add to inventory")
    fire {ItemsCheckedInToInventory.Id = s.Id; Count = count}

where the fire function simply creates a Event array from a single event :

let fire o =  
    [o :> Event]

(notice the [o:> smiley here !)

An array is returned here so that a method can fire/return several events using a simple :: syntax.

The state application can also become immutable. The function gives next state based on event and previous state :

State –> Event –> State or Func

let applyOnInventoryItem s (e: Event) =
    match e with
    | :? InventoryItemCreated as e -> {Id = e.Id; Activated = true }
    | :? InventoryItemDeactivated as e -> {s with Activated = false; }
    | _ -> s

no need for several methods here, every thing is straight forward. Match the event using its type.

The first event is a creation, so a state record is creates.

The second events copies state s with Activated set to false. No change occurs here, a copy is returned.

The _ match specifies that any other event simply return previous state.

Done.

The current state is a left fold of passed events

Sure and the replayWith method is simply here to do this :

let replayWith =
    Seq.fold

let replayInventoryItem =
    replayWith applyOnInventoryItem 
        { Id = Guid.Empty; Activated = false}

the replayInventoryItem is a function that takes a Event seq aka IEnumerable. It will start with the empty state, then for each event, call the applyOnInventoryItem function with previous state, current event, and iterate with new state.

The result is the current state.

Command handlers

The event handlers use the following functions :

let load id =
    eventStore.GetEventsForAggregate id
    |> replayInventoryItem

let save = eventStore.SaveEvents

let applyOn id version f =
    load id
    |> f
    |> save id version

load simply pass events for the aggregate with identifier id to the replayInventoryItem

save is simply a short cut for the event store SaveEvents method

applyOn loads an aggregate to current state, pass state to f, a function that returns an event seq, then save it to the event store.

Here is a sample of its use :

    member x.Handle (c: CheckInItemsToInventory) =
        checkIn c.Count
        |> applyOn c.InventoryItemId c.OriginalVersion

The checkIn function actually expect an second State argument, it signature is int –> State –> Event seq

After passing the c.Count integer argument this is now a State –> Event seq function.

When passed to the applyOn function, the state issued from the load call will be passed to it, resulting in an Event seq that will be passed to the save function.

Conclusion

There are a few things to notice in this implementation.

  1. It is very short, much shorter that C# version.
  2. There is no InventoryItem class. The InventoryItem module contains a State record, the representation of the aggregate internal state, functions to determine raised events, and functions to determine next state based on previous state and event. No base class is needed for event dispatch and uncommitted event handling.
  3. There is no repository. Actually the load and save methods do what a repository does, but it’s so simple that no class is required.

I did not talk about the read model that is a bit less interesting here.

Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
Multiple items
module Event from Microsoft.FSharp.Control

--------------------
type Event<'T> = new: unit -> Event<'T> member Trigger: arg: 'T -> unit member Publish: IEvent<'T>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate and reference type and 'Delegate: not null)> = new: unit -> Event<'Delegate,'Args> member Trigger: sender: objnull * args: 'Args -> unit member Publish: IEvent<'Delegate,'Args>

--------------------
new: unit -> Event<'T>

--------------------
new: unit -> Event<'Delegate,'Args>
namespace System
type Item = { Id: int }
Multiple items
module Event from Microsoft.FSharp.Control

--------------------
type Event = interface end

--------------------
type Event<'T> = new: unit -> Event<'T> member Trigger: arg: 'T -> unit member Publish: IEvent<'T>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate and reference type and 'Delegate: not null)> = new: unit -> Event<'Delegate,'Args> member Trigger: sender: objnull * args: 'Args -> unit member Publish: IEvent<'Delegate,'Args>

--------------------
new: unit -> Event<'T>

--------------------
new: unit -> Event<'Delegate,'Args>
type ItemsCheckedInToInventory = { Id: Guid Count: int } interface Event
Multiple items
type Guid = new: b: byte array -> unit + 6 overloads member CompareTo: value: Guid -> int + 1 overload member Equals: g: Guid -> bool + 1 overload member GetHashCode: unit -> int member ToByteArray: unit -> byte array + 1 overload member ToString: unit -> string + 2 overloads member TryFormat: utf8Destination: Span<byte> * bytesWritten: byref<int> * ?format: ReadOnlySpan<char> -> bool + 1 overload member TryWriteBytes: destination: Span<byte> -> bool + 1 overload static member (<) : left: Guid * right: Guid -> bool static member (<=) : left: Guid * right: Guid -> bool ...
<summary>Represents a globally unique identifier (GUID).</summary>

--------------------
Guid ()
Guid(b: byte array) : Guid
Guid(b: ReadOnlySpan<byte>) : Guid
Guid(g: string) : Guid
Guid(b: ReadOnlySpan<byte>, bigEndian: bool) : Guid
Guid(a: int, b: int16, c: int16, d: byte array) : Guid
Guid(a: int, b: int16, c: int16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : Guid
Guid(a: uint32, b: uint16, c: uint16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : Guid
type InventoryItemCreated = { Id: Guid } interface Event
type InventoryItemDeactivated = { Id: Guid } interface Event
type State = { Id: Guid Activated: bool }
type bool = Boolean
val fire: o: Event -> Event list
val o: Event
val checkIn: count: int -> s: State -> Event list
val count: int
val s: State
val raise: exn: Exception -> 'T
Multiple items
type InvalidOperationException = inherit SystemException new: unit -> unit + 2 overloads
<summary>The exception that is thrown when a method call is invalid for the object's current state.</summary>

--------------------
InvalidOperationException() : InvalidOperationException
InvalidOperationException(message: string) : InvalidOperationException
InvalidOperationException(message: string, innerException: exn) : InvalidOperationException
State.Id: Guid
type EventStore = abstract GetEventsForAggregate: Guid -> Event seq abstract SaveEvents: Guid -> int -> Event seq -> unit
Multiple items
val seq: sequence: 'T seq -> 'T seq

--------------------
type 'T seq = Collections.Generic.IEnumerable<'T>
type unit = Unit
val eventStore: EventStore
module Unchecked from Microsoft.FSharp.Core.Operators
val defaultof<'T> : 'T
val applyOnInventoryItem: s: State -> e: Event -> State
val e: Event
val e: InventoryItemCreated
InventoryItemCreated.Id: Guid
val e: InventoryItemDeactivated
val replayWith: (('a -> 'b -> 'a) -> 'a -> 'b seq -> 'a)
module Seq from Microsoft.FSharp.Collections
val fold<'T,'State> : folder: ('State -> 'T -> 'State) -> state: 'State -> source: 'T seq -> 'State
val replayInventoryItem: (Event seq -> State)
field Guid.Empty: Guid
val load: id: Guid -> State
val id: Guid
abstract EventStore.GetEventsForAggregate: Guid -> Event seq
val save: (Guid -> int -> Event seq -> unit)
abstract EventStore.SaveEvents: Guid -> int -> Event seq -> unit
val applyOn: id: Guid -> version: int -> f: (State -> #seq<Event>) -> unit
val version: int
val f: (State -> #seq<Event>)
type CheckInItemsToInventory = { InventoryItemId: Guid OriginalVersion: int Count: int }
Multiple items
type Entity = new: unit -> Entity member Handle: c: CheckInItemsToInventory -> unit

--------------------
new: unit -> Entity
val checkIn: c: int -> s: State -> 'a
val c: int
val failwith: message: string -> 'T
val x: Entity
val c: CheckInItemsToInventory
CheckInItemsToInventory.Count: int
CheckInItemsToInventory.InventoryItemId: Guid
CheckInItemsToInventory.OriginalVersion: int