FsCodec
Defines a minimal interface for serialization and deserialization of events for event-sourcing systems on .NET.
Provides implementation packages for writing simple yet versionable Event Contract definitions in F# using ubiquitous serializers.
Typically used in applications leveraging Equinox and/or Propulsion, but also applicable to defining DTOs for other purposes such as Web APIs.
Components
The components within this repository are delivered as multi-targeted Nuget packages supporting netstandard2.1 (F# 4.5+) profiles.
-
FsCodec Defines interfaces with trivial implementation helpers.
- No dependencies.
FsCodec.IEventCodec: defines a base interface for serializers.
FsCodec.Codec: enables plugging in custom serialization (a trivial implementation of the interface that simply delegates to a pair of encode and decode functions you supply)
FsCodec.StreamName: strongly-typed wrapper for a Stream Name, together with factory functions and active patterns for parsing same
FsCodec.StreamId: strongly-typed wrapper for a Stream Id, together with factory functions and active patterns for parsing same
-
FsCodec.Box: See FsCodec.Box.Codec; IEventCodec<obj> implementation that provides a null encode/decode step in order to enable decoupling of serialization/deserialization concerns from the encoding aspect, typically used together with Equinox.MemoryStore
- depends on
FsCodec, TypeShape >= 10
-
FsCodec.NewtonsoftJson: As described in a scheme for the serializing Events modelled as an F# Discriminated Union, enabled tagging of F# Discriminated Union cases in a versionable manner with low-dependencies using TypeShape's UnionContractEncoder
- Uses the ubiquitous
Newtonsoft.Json library to serialize the event bodies.
- Provides relevant Converters for common non-primitive types prevalent in F#
- depends on
FsCodec.Box, Newtonsoft.Json >= 13.0.3, Microsoft.IO.RecyclableMemoryStream >= 3.0.0, System.Buffers >= 4.5.1
-
FsCodec.SystemTextJson: See #38: drop in replacement that allows one to retarget from Newtonsoft.Json to the .NET Core >= v 3.0 default serializer: System.Text.Json, solely by changing the referenced namespace.
- depends on
FsCodec.Box, System.Text.Json >= 6.0.1,
Features: FsCodec
The purpose of the FsCodec package is to provide a minimal interface on which libraries such as Equinox and Propulsion can depend on in order that they can avoid forcing a specific serialization mechanism.
FsCodec.IEventData represents a single event and/or related metadata in raw form (i.e. still as a UTF8 string etc, not yet bound to a specific Event Type)
FsCodec.ITimelineEvent represents a single stored event and/or related metadata in raw form (i.e. still as a UTF8 string etc, not yet bound to a specific Event Type). Inherits IEventData, adding Index and IsUnfold in order to represent the position on the timeline that the event logically occupies.
FsCodec.IEventCodec presents Encode: 'Context option * 'Event -> IEventData and Decode: ITimelineEvent -> 'Event voption methods that can be used in low level application code to generate IEventDatas or decode ITimelineEvents based on a contract defined by 'Union
FsCodec.Codec.Create implements IEventCodec in terms of supplied encode: 'Event -> string * byte[] and decode: string * byte[] -> 'Event voption functions (other overloads are available for advanced cases)
FsCodec.Core.EventData.Create is a low level helper to create an IEventData directly for purposes such as tests etc.
FsCodec.Core.TimelineEvent.Create is a low level helper to create an ITimelineEvent directly for purposes such as tests etc.
Features: FsCodec.(Newtonsoft|SystemText)Json
Common API
The concrete implementations implement common type/member/function signatures and behavior that offer consistent behavior using either Newtonsoft.Json or System.Text.Json, emphasizing the following qualities:
- avoid non-straightforward encodings:
- tuples don't magically become arrays
- union bodies don't become arrays of mixed types like they do OOTB in JSON.NET (they become JSON Objects with named fields via
UnionEncoder, or string values via TypeSafeEnumConverter)
- don't surprise .NET developers used to
JSON.NET or System.Text.Json
- having an opinionated core set of behaviors, but don't conflict with the standard extensibility mechanisms afforded by the underlying serializer (one should be able to search up and apply answers from StackOverflow to questions regarding corner cases)
- maintain a minimal but well formed set of built in converters that are implemented per supported serializer - e.g., choices like not supporting F#
list types (although System.Text.Json v >= 6 does now provide such support)
Codec
FsCodec.NewtonsoftJson/SystemTextJson.Codec provides an implementation of IEventCodec as described in a scheme for the serializing Events modelled as an F# Discriminated Union. This yields a clean yet versionable way of managing the roundtripping events based on a contract inferred from an F# Discriminated Union Type using Newtonsoft.Json >= 13.0.3 / System.Text.Json to serialize the bodies.
Converters: Newtonsoft.Json.Converters / System.Text.Json.Serialization.JsonConverters
Explicit vs Implicit
While it's alluded to in the recommendations, it's worth calling out that the converters in FsCodec (aside from obvious exceptions like the Option and Record ones) are intended to be used by tagging the type with a JsonConverterAttribute rather than by inclusion in the global converters list of the underlying serializer.
The key effect of this is that any non-trivial mapping will manifest as the application of the relevant attribute on the type or property in question. This also aligns well with the notion of cordoning off a module Events as described in Equinox's module Aggregate documentation: types that participate in an Event union are defined and namespaced together (including any snapshot serialization contracts).
This set might be all you need ...
While this may not seem like a sufficiently large set of converters for a large app, it should be mentioned that the serializer-neutral escape hatch represented by JsonIsomorphism has resulted in this set alone proving sufficient for two major subsystems of a large e-commerce software suite. See recommendations for further expansion on this (TL;DR it does mean ruling out using some type constructs directly in event and/or binding contracts and using Anti Corruption Layer and/or event versioning techniques.
... but don't forget FSharp.SystemTextJson
The role and intention of the converters in the box in FsCodec.SystemTextJson and/or FsCodec.NewtonsoftJson has always been to be minimal but provide escape hatches; short lived shims absolutely fit within this remit. For example, with regard to System.Text.Json, over time the shimming provided has been adjusted in alignment with the STJ implementation:
It's worth calling out explicitly that there are no plans to extend the representations FsCodec.SystemTextJson can handle in any significant way over time (the advice for FsCodec.NewtonsoftJson has always been to avoid stuff outside of records, options and arrays) - if you have specific exotic corner cases and determine you need something more specifically tailored, the Converters abstraction affords you ability to mix and match as necessary for specific applications.
The single most complete set of System.Text.Json Converters is the FSharp.SystemTextJson library; it provides a much broader, well tested set of converters with a broader remit than what FsCodec is trying to succinctly address as its sweet spot. In general, there should be a smooth path to transition from using FsCodec to that as and when needed
Core converters
The respective concrete Codec packages include relevant Converter/JsonConverter in order to facilitate interoperable and versionable renderings:
-
TypeSafeEnumConverter represents discriminated union (whose cases are all nullary), as a string in a trustworthy manner (Newtonsoft.Json.Converters.StringEnumConverter permits values outside the declared values) ๐ @amjjd
-
UnionConverter represents F# discriminated unions as a single JSON object with both the tag value and the body content as named fields directly within ๐ @amjdd; System.Text.Json reimplementation ๐ @NickDarvey
NOTE: The encoding differs from that provided by Newtonsoft.Json's default converter: Newtonsoft.Json.Converters.DiscriminatedUnionConverter, which encodes the fields as an array without names, which has some pros, but many obvious cons
NOTE System.Text.Json, even in v 6.0 does not support F# unions out of the box. It's not intended to extend the representations FsCodec.SystemTextJson can handle in any significant way over time - if you have specific requirements, the powerful and complete FSharp.SystemTextJson library is likely your best option in this space.
Custom converter base classes
JsonIsomorphism - allows one to cleanly map a type's internal representation to something that the underlying serializer and converters can already cleanly handle ๐ @EirikTsarpalis
JsonPickler - removes boilerplate from simple converters, used in implementation of JsonIsomorphism ๐ @EirikTsarpalis
Newtonsoft.Json-specific low level converters
OptionConverter represents F#'s Option<'t> as a value or null; included in the standard Options.Create profile.
VerbatimUtf8JsonConverter captures/renders known valid UTF8 JSON data into a byte[] without decomposing it into an object model (not typically relevant for application level code, used in Equinox.Cosmos versions prior to 3.0).
System.Text.Json-specific low level converters
UnionOrTypeSafeEnumConverterFactory: Global converter that can apply TypeSafeEnumConverter to all Discriminated Unions that do not have cases with values, and UnionConverter to ones that have values. See this System.Text.Json issue for background information as to the reasoning behind and tradeoffs involved in applying such a policy.
RejectNullStringConverter: Global converter that rejects null string values, forcing explicit use of string option where there is a need to represent a null value
FsCodec.NewtonsoftJson.Options
FsCodec.NewtonsoftJson.Options provides a clean syntax for building a Newtonsoft.Json.JsonSerializerSettings with which to define a serialization contract profile for interoperability purposes. Methods:
CreateDefault: as per Newtonsoft.Json defaults with the following override:
DateTimeZoneHandling = DateTimeZoneHandling.Utc (default is RoundtripKind)
- no custom
IContractResolver (one is expected to use camelCase field names within records, for which this does not matter)
Create: as CreateDefault with the following difference:
- adds an
OptionConverter (see Converters, above)
Default: Default settings; same as calling Create() produces
FsCodec.SystemTextJson.Options
FsCodec.SystemTextJson.Options provides a clean syntax for building a System.Text.Json.Serialization.JsonSerializerOptions as per FsCodec.NewtonsoftJson.Options, above. Methods:
CreateDefault: configures the settings equivalent to new JsonSerializerSettings() or JsonSerializerSettings.Default, without overrides of any kind (see Create, below for the relevant differences)
Create: as CreateDefault with the following difference:
- By default, inhibits the HTML-safe escaping that
System.Text.Json provides as a default by overriding Encoder with System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
(camelCase = true): opts into camel case conversion for PascalCased properties and Dictionary keys
(autoTypeSafeEnumToJsonString = true): triggers usage of TypeSafeEnumConverter for any F# Discriminated Unions that only contain nullary cases. See AutoUnionTests.fs for examples
(autoUnionToJsonObject = true): triggers usage of a UnionConverter to round-trip F# Discriminated Unions (with at least a single case that has a body) as JSON Object structures. See AutoUnionTests.fs for examples
(rejectNullStrings = true): triggers usage of RejectNullStringConverter to reject null as a value for strings (string option can be used to handle them explicitly).
Default: Default settings; same as calling Create() produces (same intent as JsonSerializerOptions.Default)
Serdes
FsCodec.SystemTextJson/NewtonsoftJson.Serdes provides light wrappers over (JsonConvert|JsonSerializer).(Des|S)erialize(Object)? based on an explicitly supplied serialization profile created by Options.Create (above), or using Options.Default. This enables one to smoothly switch between System.Text.Json vs Newtonsoft.Json serializers with minimal application code changes, while also ensuring consistent and correct options get applied in each case. Methods:
Serialize<T>: serializes an object per its type using the settings defined in Options.Create
Deserialize<T>: deserializes an object per its type using the settings defined in Options.Create
Options: Allows one to access the JsonSerializerSettings/JsonSerializerOptions used by this instance.
Usage of Converters with ASP.NET Core
ASP.NET Core's out-of-the-box behavior is to use System.Text.Json. One can explicitly opt to use Newtonsoft.Json via the Microsoft.AspNetCore.Mvc.NewtonsoftJson package's AddNewtonsoftJson by adjusting one's .AddMvc().
If you follow the policies covered in the rest of the documentation here, your DTO types (and/or types in your module Events that you surface while you are scaffolding and/or hacking without an anti-corruption layer) will fall into one of two classifications:
- Types that have an associated Converter explicitly annotated (e.g., DU types bear an associated
UnionConverter, TypeSafeEnumConverter or JsonIsomorphism-based custom converter, custom types follow the conventions or define a JsonIsomorphism-based converter)
- Types that require a global converter to be registered. While it may seem that the second set is open-ended and potentially vast, experience teaches that you want to keep it minimal.. This boils down to:
- records, arrays and all other good choices for types Just Work already
Nullable<MyType>: Handled out of the box by both NSJ and STJ - requires no converters, provides excellent interop with other CLR languages. Would recommend.
MyType option: Covered by the global OptionConverter for Newtonsoft, handled intrinsically by System.Text.Json versions >= 6 (see below for a clean way to add them to the default MVC view rendering configuration). Note that while this works well with ASP.NET Core, it may be problematic if you share contracts (yes, not saying you should) or rely on things like Swashbuckle that will need to be aware of the types when they reflect over them.
The bottom line is that using exotic types in DTOs is something to think very hard about before descending into. The next sections are thus only relevant if you decide to add that extra complexity to your system...
ASP.NET Core with Newtonsoft.Json
Hence the following represents the recommended default policy:-
/// Define a Serdes instance with a given policy somewhere (globally if you need to do explicit JSON generation)
let serdes = FsCodec.NewtonsoftJson.Serdes.Default
services.AddMvc(fun options -> ...
).AddNewtonsoftJson(fun options ->
// Borrow the Converters from the Options the Serdes is holding
serdes.Options.Converters |> Seq.iter options.SerializerSettings.Converters.Add
// OR, in the trivial case: Options.Default.Converters |> Seq.iter options.SerializerSettings.Converters.Add
) |> ignore
This adds all the converters used by the serdes serialization/deserialization policy (currently only FsCodec.NewtonsoftJson.OptionConverter) into the equivalent managed by ASP.NET.
ASP.NET Core with System.Text.Json
The equivalent for the native System.Text.Json, as of v6, thanks to the great work of the .NET team, is presently a no-op.
The following illustrates how to opt into autoTypeSafeEnumToJsonString and/or autoUnionToJsonObject modes, and rejectNullStrings for the rendering of View Models by ASP.NET:
// Default behavior throws an exception if you attempt to serialize a DU or TypeSafeEnum without an explicit JsonConverterAttribute
// let serdes = FsCodec.SystemTextJson.Serdes.Default
// If you use autoTypeSafeEnumToJsonString = true or autoUnionToJsonObject = true, serdes.Serialize / Deserialize applies the relevant converters
let options = FsCodec.SystemTextJson.Options.Create(autoTypeSafeEnumToJsonString = true, autoUnionToJsonObject = true, rejectNullString = true)
let serdes = FsCodec.SystemTextJson.Serdes options
services.AddMvc(fun options -> ...
).AddJsonOptions(fun options ->
// Register the converters from the Options passed to the `serdes` above
serdes.Options.Converters |> Seq.iter options.JsonSerializerOptions.Converters.Add
) |> ignore
Examples: FsCodec.(Newtonsoft|SystemText)Json
There's a test playground in tests/FsCodec.NewtonsoftJson.Tests/Examples.fsx. It's highly recommended to experiment with conversions using FSI. (Also, PRs adding examples are much appreciated...)
There's an equivalent of that for FsCodec.SystemTextJson: tests/FsCodec.SystemTextJson.Tests/Examples.fsx.
Examples of using Serdes to define a contract
In a contract assembly used as a way to supply types as part of a client library, one way of encapsulating the conversion rules that need to be applied is as follows:
Simple contracts that tag all types or fields necessitating Converters directly and only records and options
The minimal code needed to define helpers to consistently roundtrip where one only uses simple types is to simply state" _Please use FsCodec.NewtonsoftJson.Serdes to encode/decode JSON payloads correctly. However, an alternate approach is to employ the convention of providing a pair of helper methods alongside the type :-
open FsCodec.SystemTextJson // or FsCodec.NewtonsoftJson if you prefer and/or have legacy converters etc
module Contract =
type Item = { value: string option }
// No special policies required as we are using standard types
let private serdes = Serdes Options.Default
// implies default settings from Options.Create(), i.e., includes UnsafeRelaxedJsonEscaping
let serialize (x: Item): string = serdes.Serialize x
// implies default settings from Options.Create()
let deserialize (json: string) = serdes.Deserialize json
More advanced case necessitating a custom converter
While it's hard to justify the wrapping in the previous case, this illustrates how one can employ the same basic layout yet override a setting (register a necessary custom Newtonsoft.Json.Converter type):
module Contract =
type Item = { value: string option; other: TypeThatRequiresMyCustomConverter }
/// Options to be used within this contract - note the Pascal Cased Value property compared to the previous record definition
let private options = Options.Create(converters = [| MyCustomConverter() |], camelCase = true)
let private serdes = Serdes options
let serialize (x: Item) = serdes.Serialize x
let deserialize (json: string): Item = serdes.Deserialize json
Encoding and conversion of F# types
Recommended round-trippable constructs
Newtonsoft.Json, thanks to its broad usage throughout .NET systems has well known (with some idiosyncratic quirks) behaviors for most common types one might use for C# DTOs.
Normal primitive F#/.NET such as bool, byte, int16, int, int64, float32 (Single), float (Double), decimal work as expected.
The default settings for FsCodec applies Json.NET's default behavior, which is to render fields that have a null or null-equivalent value with the value null. This behavior can be overridden via Options(ignoreNulls = true), which will cause such JSON fields to be omitted.
The recommendations here apply particularly to Event Contracts - the data in your store will inevitably outlast your code, so being conservative in the complexity of one's encoding scheme is paramount. Explicit is better than Implicit.
| Type kind |
TL;DR |
Notes |
Example input |
Example output |
't[] |
As per C# |
Don't forget to handle null |
[ 1; 2; 3] |
[1,2,3] |
DateTimeOffset |
Roundtrips cleanly |
The default Options.Create requests RoundtripKind |
DateTimeOffset.Now |
"2019-09-04T20:30:37.272403+01:00" |
Nullable<'t> |
As per C#; Nullable() -> null, Nullable x -> x |
OOTB Json.NET and STJ roundtrip cleanly. Works with Options.CreateDefault(). Worth considering if your contract does not involve many option types |
Nullable 14 |
14 |
't option |
Some null,None -> null, Some x -> x with the converter Options.Create() adds |
OOTB Json.NET does not roundtrip option types cleanly; Options.Create wires in an OptionConverter by default in FsCodec.NewtonsoftJson NOTE Some null will produce null, but deserialize as None - i.e., it's not round-trippable |
Some 14 |
14 |
string |
As per C#; need to handle null. Can opt into rejecting null values with (rejectNullStrings = true) |
One can use a string option to map null and Some null to None |
"Abc" |
"Abc" |
| types with unit of measure |
Works well (doesnt encode the unit) |
Unit of measure tags are only known to the compiler; Json.NET does not process the tags and treats it as the underlying primitive type |
54<g> |
54 |
FSharp.UMX tagged string, DateTimeOffset |
Works well |
FSharp.UMX enables one to type-tag string and DateTimeOffset values using the units of measure compiler feature, which Json.NET will render as if they were unadorned |
SkuId.parse "54-321" |
"000-054-321" |
| records |
Just work |
For System.Text.Json v 4.x, usage of [<CLIMutable>] or a custom JsonRecordConverter was once required |
{| a = 1; b = Some "x" |} |
"{"a":1,"b":"x"}" |
| Nullary unions (Enum-like DU's without bodies) |
Tag type with TypeSafeEnumConverter |
Works well - guarantees a valid mapping, as opposed to using a System.Enum and StringEnumConverter, which can map invalid values and/or silently map to 0 etc |
State.NotFound |
"NotFound" |
| Discriminated Unions (where one or more cases has a body) |
Tag type with UnionConverter |
This format can be readily consumed in Java, JavaScript and Swift. Nonetheless, exhaust all other avenues before considering encoding a union in JSON. The "case" label id can be overridden. |
Decision.Accepted { result = "54" } |
{"case": "Accepted","result":"54"} |
Unsupported types and/or constructs
The mechanisms in the previous section have proven themselves sufficient for diverse systems inside and outside Jet. Here, we summarize some problematic constructs, with suggestions for alternate approaches to apply in preference.
| Type kind |
TL;DR |
Example input |
Example output |
Notes |
't list |
Don't use; use 't[] |
[ 1; 2; 3] |
[1,2,3] |
While the happy path works, null or missing field maps to a null object rather than [] [which is completely wrong from an F# perspective]. (System.Text.Json v >= 6 does now handle them correctly, but arrays are still the preferred representation, and there is no plan at present to have FsCodec.NewtonsoftJson provide support for it in the name of interoperability) |
DateTime |
Don't use; use DateTimeOffset |
|
|
Round-tripping can be messy, wrong or lossy; DateTimeOffset covers same use cases |
Guid or FSharp.UMX tagged Guid |
don't use; wrap as a reference type and use a JsonIsomorphism, or represent as a tagged string |
Guid.NewGuid() |
"ba7024c7-6795-413f-9f11-d3b7b1a1fe7a" |
If you wrap the value in a type, you can have that roundtrip with a specific format via a Converter implemented as a JsonIsomorphism. Alternately, represent in your contract as a FSharp.UMX tagged-string. |
maps/Dictionary etc. |
avoid; prefer arrays |
|
|
As per C#; not always the best option for many reasons, both on the producer and consumer side. Json.NET has support for various maps with various idiosyncracies typically best covered by Stack Overflow, but often a list of records is clearer For System.Text.Json, use an IDictionary<'K, 'V> or Dictionary<'K, 'V> |
| tuples |
Don't use; use records |
(1,2) |
{"Item1":1,"Item2":2} |
While converters are out there, using tuples in contracts of any kind is simply Not A Good Idea |
TypeSafeEnumConverter
TypeSafeEnumConverter is intended to provide for Nullary Unions (also known as Type Safe Enums, especially in Java circles),
what Newtonsoft.Json does for enum values with the StringEnumConverter. This is motivated by the fact that the out
of the box behaviors are unsatisfactory for both Newtonsoft.Json and for System.Text.Json (but, for different, unfortunate reasons...).
Out of the box behavior: Newtonsoft.Json
By default, a Nullary Union's default rendering via Newtonsoft.Json, without any converters in force,
is a generic rendering that treats the values as DU values with bodies are treated.
type Status = Initial | Active
type StatusMessage = { name: string option; status: Status }
let status = { name = None; status = Initial }
// The problems here are:
// 1. the value has lots of noise, which consumes storage space, and makes parsing harder
// 2. other languages which would naturally operate on the string value if it was presented as such will have problems parsing
// 3. it's also simply unnecessarily hard to read as a human
serdes.Serialize status
// "{"name":null,"status":{"Case":"Initial"}}"
// If we pretty-print it, things get worse, not better:
let serdesFormatted = Serdes(Options.Create(indent = true))
serdesFormatted.Serialize(status)
// "{
// "name": null,
// "status": {
// "Case": "Initial"
// }
// }
Out of the box behavior: System.Text.Json
System.Text.Json has no intrinsic behavior. Some lament this, but it's also unambiguous:
// Without any converters in force, Serdes exposes System.Text.Json's internal behavior, which throws:
type Status = Initial | Active
type StatusMessage = { name: string option; status: Status }
let status = { name = None; status = Initial }
serdes.Serialize status
// System.NotSupportedException: F# discriminated union serialization is not supported. Consider authoring a custom converter for the type.
// at System.Text.Json.Serialization.Converters.FSharpTypeConverterFactory.CreateConverter(Type typeToConvert, JsonSerializerOptions options)
TypeSafeEnumConverter behavior
The TypeSafeEnumConverter alters this incomplete and/or inconsistent behavior to encode values directly as StringEnumConverter does for enum (System.Enum), for both serializers:
FsCodec.NewtonsoftJson.TypeSafeEnumConverter
For Newtonsoft.Json, the recommended approach is to tag each Nullary Union Type with a JsonConverter attribute:
let serdes2 = Serdes.Default
[<Newtonsoft.Json.JsonConverter(typeof<TypeSafeEnumConverter>)>]
type Status2 = Initial | Active
type StatusMessage2 = { name: string option; status: Status2 }
let status2 = { name = None; status = Initial }
serdes2.Serialize status2
// "{"name":null,"status":"Initial"}"
It's possible to automate this across all types by registering a single custom converter:
// A single registered converter supplied when creating the Serdes can automatically map all Nullary Unions to strings:
open FsCodec.NewtonsoftJson
let serdesWithConverter = Serdes(Options.Create(TypeSafeEnumConverter()))
// NOTE: no JsonConverter attribute
type Status3 = Initial | Active
type StatusMessage3 = { name: string option; status: Status3 }
let status3 = { name = None; status = Initial }
serdesWithConverter.Serialize status3
// "{"name":null,"status":"Initial"}"
FsCodec.SystemTextJson.TypeSafeEnumConverter<'T>
For System.Text.Json, the process is a little different, as Converters in System.Text.Json are expected to work for a single type only.
Using the same type that was rejected by out-of-the-box System.Text.Json earlier:
type Status = Initial | Active
type StatusMessage = { name: string option; status: Status }
let status = { name = None; status = Initial }
We can supply a Converter via the Options:
open FsCodec.SystemTextJson
let serdesWithConverter = Serdes <| Options.Create(TypeSafeEnumConverter<Status>())
serdesWithConverter.Serialize status
// "{"name":null,"status":"Initial"}"
Rather than having to supply lots of such converter isntances, the recommendation is to tag each type:
```fsharp
let serdes = Fscodec.SystemTextJson.Serdes.Default
// NOTE in System.Text.Json, the converter is generic, and must reference the actual type (here: Status2)
[<System.Text.Json.Serialization.JsonConverter(typeof<TypeSafeEnumConverter<Status2>>)>]
type Status2 = Initial | Active
type StatusMessage2 = { name: string option; status: Status2 }
let status2 = { name = None; status = Initial }
serdes.Serialize status2
Using the TypeSafeEnumConverter in FsCodec.SystemTextJson, each Nullary Union Type needs it's own converter registered.
open FsCodec.SystemTextJson
// NOTE: Every Nullary Union Type needs a specific instantiation of the generic converter registered:
let serdesWithConverter = Serdes <| Options.Create(TypeSafeEnumConverter<Status>())
serdesWithConverter.Serialize status
// "{"name":null,"status":"Initial"}"
The equivalent of registering a single global TypeSafeEnumConverter is the autoTypeSafeEnumToJsonString setting on the Options:
open FsCodec.SystemTextJson
let options = Options.Create(autoTypeSafeEnumToJsonString = true, rejectNullStrings = true)
let serdes3 = Serdes options
type Status3 = Initial | Active
type StatusMessage3 = { name: string option; status: Status3 }
let status3 = { name = None; status = Initial }
serdes3.Serialize status3
// "{"name":null,"status":"Initial"}"
Custom converters using JsonIsomorphism
JsonIsomorphism enables one to express the Reading and Writeing of the JSON for a type in terms of another type. As alluded to above, rendering and parsing of Guid values can be expressed succinctly in this manner. The following Converter, when applied to a field, will render it without dashes in the rendered form:
type GuidConverter() =
inherit JsonIsomorphism<Guid, string>()
override _.Pickle g = g.ToString "N"
override _.UnPickle g = Guid.Parse g
JsonIsomporphism can also be used together with FsCodec.TypeSafeEnum, to deal with mapping of values from string to Nullary Unions that don't fit in the easy cases.
[<JsonConverter(typeof<TypeSafeEnumConverter>)>]
type Outcome = Joy | Pain | Misery
type Message = { name: string option; outcome: Outcome }
let value = { name = Some null; outcome = Joy}
serdes.Serialize value
// {"name":null,"outcome":"Joy"}
serdes.Deserialize<Message> """{"name":null,"outcome":"Joy"}"""
// val it : Message = {name = None; outcome = Joy;}
By design, we throw when a value is unknown. Often this is the correct design. If, and only if, your software can do something useful with catch-all case, see the technique in OutcomeWithOther (below)
serdes.Deserialize<Message> """{"name":null,"outcome":"Discomfort"}"""
// throws System.Collections.Generic.KeyNotFoundException: Could not find case 'Discomfort' for type 'FSI_0012+Outcome'
TypeSafeEnum fallback converters using JsonIsomorphism
While, in general, one wants to version contracts such that invalid values simply don't arise, in some cases you want to explicitly handle out of range values.
Here we implement a converter as a JsonIsomorphism to achieve such a mapping
[<JsonConverter(typeof<OutcomeWithCatchAllConverter>)>]
type OutcomeWithOther = Joy | Pain | Misery | Other
and OutcomeWithCatchAllConverter() =
inherit JsonIsomorphism<OutcomeWithOther, string>()
override _.Pickle v =
FsCodec.TypeSafeEnum.toString v
override _.UnPickle json =
json
|> FsCodec.TypeSafeEnum.tryParse<OutcomeWithOther>
|> Option.defaultValue Other
type Message2 = { name: string option; outcome: OutcomeWithOther }
Because the type is tagged with a Converter attribute, valid values continue to be converted correctly:
let value2 = { name = Some null; outcome = Joy}
serdes.Serialize value2
// {"name":null,"outcome":"Joy"}
serdes.Deserialize<Message2> """{"name":null,"outcome":"Joy"}"""
// val it : Message = {name = None; outcome = Joy;}
More importantly, the formerly invalid value now gets mapped to our fallback value (Other) as intended.
serdes.Deserialize<Message2> """{"name":null,"outcome":"Discomfort"}"""
// val it : Message = {name = None; outcome = Other;}
Features: IEventCodec
See tests/FsCodec.SystemTextJson.Tests/Examples.fsx for a worked example suitable for playing with in F# interactive based on the following tutorial
/// Defines a contract interpreter that encodes and/or decodes events representing the known set of events borne by a stream category
type IEventCodec<'Event, 'Format, 'Context> =
/// Encodes a 'Event instance into a 'Format representation
abstract Encode: context: 'Context * value: 'Event -> IEventData<'Format>
/// Decodes a formatted representation into a 'Event instance. Does not throw exception on undefined EventTypes
abstract Decode: encoded: ITimelineEvent<'Format> -> 'Event voption
IEventCodec represents a standard contract for the encoding and decoding of events used in event sourcing and event based notification scenarios:
- encoding pending/tentative "source of truth" events ('Facts') in Event Sourced systems (including encoding ones on the way to the store that are not yet accepted on a Timeline) - (see
FsCodec.IEventData)
- decoding event records from an Event Store in a programming model, which involves mapping from the source event together with contextual information (see
FsCodec.ITimelineEvent) such as:
- The event type, which signifies the event that has taken place (if you're familiar with ADTs, this maps to the Discriminator in a Discriminated Union)
- the core event data (often encoded as JSON, protobufs etc), the schema for which typically varies by event type
- event metadata (contextual information optionally stored alongside the event)
- the
Timestamp at which the event was generated
- the
Index representing the position of this event within the sequence of events on the timeline represented by the stream from which one is hydrating the event
- Correlation/causation identifiers for the activity that triggered the event
- routing and filtering of events for the purpose of managing projections, notification or reactions to events. Such events may either emanate directly from an Event Store's timeline as in the preceding cases, or represent versioned summary events
Pending and timeline Events share the following common contract:
/// Common form for either a Domain Event or an Unfolded Event, without any context regarding its place in the timeline of events
type IEventData<'Format> =
/// The Event Type, used to drive deserialization
abstract member EventType: string
/// Event body, as UTF-8 encoded JSON ready to be injected into the Store
abstract member Data: 'Format
/// Optional metadata (null, or same as Data, not written if missing)
abstract member Meta: 'Format
/// Application-generated identifier used to drive idempotent writes based on deterministic Ids and/or Request Id
abstract member EventId: System.Guid
/// The Correlation Id associated with the flow that generated this event. Can be `null`
abstract member CorrelationId: string
/// The Causation Id associated with the flow that generated this event. Can be `null`
abstract member CausationId: string
/// The Event's Creation Time (as defined by the writer, i.e. in a mirror, this is intended to reflect the original time)
/// - For EventStore, this value is not honored when writing; the server applies an authoritative timestamp when accepting the write.
abstract member Timestamp: System.DateTimeOffset
Events from a versioned feed and/or being loaded from an Event Store bring additional context beyond the base information in IEventData
/// Represents a Domain Event or Unfold, together with it's 0-based Index in the event sequence
type ITimelineEvent<'Format> =
inherit IEventData<'Format>
/// The 0-based index into the event sequence of this Event
abstract member Index: int64
/// Application-supplied context related to the origin of this event
abstract member Context: obj
/// Indicates this is not a true Domain Event, but actually an Unfolded Event based on the State inferred from the Events up to and including that at Index
abstract member IsUnfold: bool
Contracts for parsing / routing event records
See a scheme for the serializing Events modelled as an F# Discriminated Union for details of the representation scheme used for the events when using FsCodec.NewtonsoftJson.Codec.Create. We'll use the following example contract for the illustration:
module Events =
type Added = { item: string }
type Removed = { name: string }
type Event =
| Added of Added
| Removed of Removed
interface TypeShape.UnionContract.IUnionContract
let codec = Store.codec<Event>
where Store refers to a set of infrastructure helpers:
namespace global
open FsCodec.SystemTextJson
module Store =
type Event = FsCodec.ITimelineEvent<EventBody>
// Many stores use a ReadOnlyMemory<byte> to represent a UTF-8 encoded JSON event body
// System.Text.Json.JsonElement can be a useful alternative where the store is JSON based
and EventBody = ReadOnlyMemory<byte>
and Codec<'E when 'E :> TypeShape.UnionContract.IUnionContract> = FsCodec.IEventCodec<'E, EventBody, unit>
// Opt in to:
// - mapping Type Safe Enums (F# Unions where the cases have no bodies) to/from Strings
// - mapping other F# Unions using the UnionConverter with default settoings
// TOCONSIDER avoid using this automatic behavior, and instead let the exception that System.Text.Json
// produces trigger adding a JsonConverterAttribute for each type as Documentation
let private options = Options.Create(autoTypeSafeEnumToJsonString = true, autoUnionToJsonObject = true)
let serdes = Serdes options
let codec<'E when 'E :> TypeShape.UnionContract.IUnionContract> : Codec<'E> =
Codec.Create(serdes = serdes)
// OR, if your Store uses JsonElement bodies
// CodecJsonElement.Create(serdes = serdes)
Having a common set of helpers allows one to analyse the encoding policies employed per aggregate as they inevitably evolve over time.
The example event stream contract above uses a ClientId type which (while being a string at heart) represents the identifier for a specific entity. We use the FSharp.UMX library that leans on the F# units of measure feature to tag the strings such that they can't be confused with other identifiers - think of it as a type alias on steroids.
open FSharp.UMX
type [<Measure>] clientId
type ClientId = string<clientId>
module ClientId =
let parse (str: string): ClientId = % str
let toString (value: ClientId): string = % value
let (|Parse|) = ClientId.parse
Stream naming conventions
The de-facto standard Event Store EventStore.org and its documentation codifies the following convention for the naming of streams:-
Where:
{Category} represents a high level contract/grouping; all stream names starting with {Category}- are the same category. Must not contain any - characters.
- (hyphen/minus) represents the by-convention standard separator between category and identifier
{StreamId} represents the identity of the Aggregate / Aggregate Root instance for which we're storing the events within this stream. The _ character is used to separate composite ids; see the code.
The StreamName module will reject invalid values by throwing exceptions when fields have erroneously embedded - or _ values.
It's important to apply some consideration in mapping from values in your domain to a StreamName. Domain values might include characters such as - (which may cause issues with EventStoreDb's $by_category projections) and/or arbitrary Unicode chars (which may not work well for other backing stores e.g. if CosmosDB were to restrict the character set that may be used for a Partition Key). You'll also want to ensure it's appropriately cleansed, validated and/or canonicalized to cover SQL Injection and/or XSS concerns. In short, no, you shouldn't just stuff an email address into the {Identifier} portion.
FsCodec.StreamName: presents the following set of helpers that are useful for splitting and filtering Stream Names by Categories and/or Identifiers. Similar helpers would of course make sense in other languages e.g. C#:
// Type aliases for a type-tagged `string`
type [<Measure>] streamName
type StreamName = string<streamName>
module StreamName =
let toString (streamName: StreamName): string = UMX.untag streamName
// Validates and maps a trusted Stream Name consisting of a Category and an Id separated by a '-` (dash)
// Throws InvalidArgumentException if it does not adhere to that form
let parse (rawStreamName: string): StreamName = ...
// Recommended way to specify a stream identifier; a category identifier and a streamId representing the aggregate's identity
// category is separated from id by `-`
let create (category: string) streamId: StreamName = ...
// Composes a StreamName from a category and > 1 name elements.
// category is separated from the streamId by '-'; elements are separated from each other by '_'
let compose (category: string) (streamIdElements: string[]): StreamName = ...
/// Extracts the category portion of the StreamName
let category (x: StreamName): string = ...
let (|Category|) = category
/// Splits a well-formed Stream Name of the form <c>{category}-{streamId}</c> into its two elements.
/// Throws InvalidArgumentException if it does not adhere to the well known format (i.e. if it was not produced by `parse`).
/// Inverse of <c>create</c>
let split (streamName: StreamName): struct (string * StreamId) = ...
/// Splits a well-formed Stream Name of the form <c>{category}-{streamId}</c> into its two elements.
/// Throws InvalidArgumentException if the stream name is not well-formed.
/// Inverse of <c>create</c>
let (|Split|): StreamName -> struct (string * StreamId) = split
/// Yields the StreamId, if the Category matches the specified one
let tryFind categoryName (x: StreamName): StreamId voption = ...
The StreamId part's key helpers are as follows:
/// Represents the second half of a canonical StreamName, i.e., the streamId in "{categoryName}-{streamId}"
type StreamId = string<streamId>
and [<Measure>] streamId
/// Helpers for composing and rendering StreamId values
module StreamId =
/// Any string can be a StreamId; parse/dec/Elements.split will judge whether it adheres to a valid form
let create: string -> StreamId = UMX.tag
/// Render as a string for external use
let toString: StreamId -> string = UMX.untag
/// Generate a StreamId from a single application-level id, given a rendering function that maps to a non empty fragment without embedded `_` chars
let gen (f: 'a -> string): 'a -> StreamId = ...
/// Generate a StreamId from a tuple of application-level ids, given two rendering functions that map to a non empty fragment without embedded `_` chars
let gen2 f1 f2: 'a * 'b -> StreamId = ...
/// Generate a StreamId from a triple of application-level ids, given three rendering functions that map to a non empty fragment without embedded `_` chars
let gen3 f1 f2 f3: 'a * 'b * 'c -> StreamId = ...
/// Generate a StreamId from a 4-tuple of application-level ids, given four rendering functions that map to a non empty fragment without embedded `_` chars
let gen4 f1 f2 f3 f4: 'a * 'b * 'c * 'd -> StreamId = ...
/// Validates and extracts the StreamId into a single fragment value
/// Throws if the item embeds a `_`, is `null`, or is empty
let parseExactlyOne (x: StreamId): string = ...
/// Validates and extracts the StreamId into a single fragment value
/// Throws if the item embeds a `_`, is `null`, or is empty
let (|Parse1|) (x: StreamId): string = ...
/// Splits a StreamId into the specified number of fragments.
/// Throws if the value does not adhere to the expected fragment count.
let parse count (x: StreamId): string[] =
let xs = Elements.split x
if xs.Length <> count then
invalidArg "x" (sprintf "StreamId '{%s}' must have {%d} elements, but had {%d}." (toString x) count xs.Length)
xs
/// Splits a StreamId into an expected number of fragments.
/// Throws if the value does not adhere to the expected fragment count.
let (|Parse|) count: StreamId -> string[] = parse count
/// Extracts a single fragment from the StreamId. Throws if the value is composed of more than one item.
let dec f (x: StreamId) = parseExactlyOne x |> f
/// Extracts 2 fragments from the StreamId. Throws if the value does not adhere to that expected form.
let dec2 f1 f2 (x: StreamId) = let xs = parse 2 x in struct (f1 xs[0], f2 xs[1])
/// Extracts 3 fragments from the StreamId. Throws if the value does not adhere to that expected form.
let dec3 f1 f2 f3 (x: StreamId) = let xs = parse 3 x in struct (f1 xs[0], f2 xs[1], f3 xs[2])
/// Extracts 4 fragments from the StreamId. Throws if the value does not adhere to that expected form.
let dec4 f1 f2 f3 f4 (x: StreamId) = let xs = parse 4 x in struct (f1 xs[0], f2 xs[1], f3 xs[2], f4 xs[3])
module Stream / module Reactions: Contracts for parsing / routing event records
The following is a set of individually small helpers that work together to allow one to succinctly extract relevant events from batches being handled in reactions.
See the StreamName/StreamId section above for the underlying interfaces.
(* Stream id generation/parsing logic. Normally kept private; Reactions module exposes relevant parsers to the wider application *)
module private Stream =
// By convention, each contract defines a 'category' used as the first part of the stream name (e.g. `"Favorites-ClientA"`)
let [<Literal>] Category = "Favorites"
/// Generates a strongly typed StreamId from the supplied Id
let id: ClientId -> FsCodec.StreamId = FsCodec.StreamId.gen ClientId.toString
/// Maps from an app level identifier to a stream name as used when storing events in that stream
/// Not normally necessary - typically you generate StreamIds, and you'll load from something that knows the Category
let name: ClientId -> FsCodec.StreamName = id >> FsCodec.StreamName.create Category
/// Inverse of `id`; decodes a StreamId into its constituent parts; throws if the presented StreamId does not adhere to the expected format
let decodeId: FsCodec.StreamId -> ClientId = FsCodec.StreamId.dec ClientId.parse
/// Inspects a stream name; if for this Category, decodes the elements into application level ids. Throws if it's malformed.
let decode: FsCodec.StreamName -> ClientId voption = FsCodec.StreamName.tryFind Category >> ValueOption.map decodeId
module Reactions =
/// Active Pattern to determine whether a given {category}-{streamId} StreamName represents the stream associated with this Aggregate
/// Yields a strongly typed id from the streamId if the Category matches
let [<return: Struct>] (|For|_|) = Stream.decode
let private dec = Streams.codec<Events.Event>
/// Yields decoded events and relevant strongly typed ids if the Category of the Stream Name matches
let [<return: Struct>] (|Decode|_|) = function
| struct (For clientId, _) & Streams.Decode dec events -> ValueSome struct (clientId, events)
| _ -> ValueNone
Decoding events
Given the following example events from across streams:
let utf8 (s: string) = System.Text.Encoding.UTF8.GetBytes(s)
let streamForClient c = Stream.name (ClientId.parse c)
let events = [
Stream.name (ClientId.parse "ClientA"), FsCodec.Core.TimelineEvent.Create(0L, "Added", utf8 """{ "item": "a" }""")
streamForClient "ClientB", FsCodec.Core.TimelineEvent.Create(0L, "Added", utf8 """{ "item": "b" }""")
FsCodec.StreamName.parse "Favorites-ClientA", FsCodec.Core.TimelineEvent.Create(1L, "Added", utf8 """{ "item": "b" }""")
streamForClient "ClientB", FsCodec.Core.TimelineEvent.Create(1L, "Added", utf8 """{ "item": "a" }""")
streamForClient "ClientB", FsCodec.Core.TimelineEvent.Create(2L, "Removed", utf8 """{ "item": "a" }""")
FsCodec.StreamName.compose "Favorites" [| "ClientB" |], FsCodec.Core.TimelineEvent.Create(3L, "Exported", utf8 """{ "count": 2 }""")
FsCodec.StreamName.parse "Misc-x", FsCodec.Core.TimelineEvent.Create(0L, "Dummy", utf8 """{ "item": "z" }""")
]
and the helpers defined above, we can route and/or filter them as follows:
```fsharp
// When we obtain events from an event store via streaming notifications, we typically receive them as ReadOnlyMemory<byte> bodies
type Event = FsCodec.ITimelineEvent<EventBody>
and EventBody = ReadOnlyMemory<byte>
and Codec<'E> = FsCodec.IEventCodec<'E, EventBody, unit>
let streamCodec<'E when 'E :> TypeShape.UnionContract.IUnionContract> : Codec<'E> =
Codec.Create<'E>(serdes = Store.serdes)
let dec = streamCodec<Events.Event>
let [<return:Struct>] (|DecodeEvent|_|) (codec: Codec<'E>) event = codec.Decode event
let runCodecExplicit () =
for stream, event in events do
match stream, event with
| Reactions.For clientId, DecodeEvent dec e ->
printfn $"Client %s{ClientId.toString clientId}, event %A{e}"
| FsCodec.StreamName.Split struct (cat, sid), e ->
printfn $"Unhandled Event: Category %s{cat}, Ids %s{FsCodec.StreamId.toString sid}, Index %d{e.Index}, Event: %A{e.EventType}"
The Reactions.For clientId bit above is the inverse of the Stream.name function. It parses a StreamName
back to the the application-level identifiers (the ClientId type), _but only if the Category
part of the name matches (i.e., the stream name StartsWith("Favorites-")). While this may seem
like a lot of busywork, it pays off when you have multiple stream categories, each with different identifiers (or
cases where you have a complex identifiers, e.g., where you have a Stream Name that's composed of a Tenant Id and a User Id)
invoking runCodecExplicit () yields:
Client ClientA, event Added {item = "a";}
Client ClientB, event Added {item = "b";}
Client ClientA, event Added {item = "b";}
Client ClientB, event Added {item = "a";}
Client ClientB, event Removed {name = null;}
Unhandled Event: Category Favorites, Id ClientB, Index 3, Event: "Exported"
Unhandled Event: Category Misc, Id x, Index 0, Event: "Dummy"
There are two events that we were not able to decode, for varying reasons:
"Misc-x", FsCodec.Core.TimelineEvent.Create(0L, "Dummy", utf8 """{ "item": "z" }""") represents an Event that happens to pass through our event processor that we don't want to decode and/or handle - we don't need to define a contract type for
"Favorites" "ClientB", FsCodec.Core.TimelineEvent.Create(3L, "Exported", utf8 """{ "count": 2 }""") represents an Event that has recently been defined in the source system, but not yet handled by the processor. In the event of such an unclassified event occurring within a stream contract we want to know when we're not handling a given event. That's trapped above and logged as Unhandled Event: Category Favorites, Id ClientB, Index 3, Event: "Exported".
Note however, that we don't have a clean way to trap the data and log it. See Logging unmatched events for an example of how one might log such unmatched events
Adding Matchers to the Event Contract
We can clarify the consuming code a little by adding further helper Active Patterns alongside the event contract :-
module ReactionsBasic =
let dec = streamCodec<Events.Event>
let (|DecodeSingle|_|): FsCodec.StreamName * Event -> (ClientId * Events.Event) option = function
| Reactions.For clientId, DecodeEvent dec event -> Some (clientId, event)
| _ -> None
That boxes off the complex pattern matching close to the contract itself, and lets us match on the events in a handler as follows:
let reactSingle (clientId: ClientId) (event: Events.Event) =
printfn $"Client %s{ClientId.toString clientId}, event %A{event}"
let runCodecMatch () =
for streamName, event in events do
match streamName, event with
| ReactionsBasic.DecodeSingle (clientId, event) ->
reactSingle clientId event
| FsCodec.StreamName.Split (cat, sid), e ->
printfn $"Unhandled Event: Category %s{cat}, Ids {FsCodec.StreamId.toString sid}, Index %d{e.Index}, Event: %s{e.EventType} "
Processing Reactions, Logging unmatched events
The following standard helpers (which use the Serilog library), can be used to selectively layer on some logging when run with logging upped to Debug level:
module Streams =
// Events coming from streams are carried as a TimelineEvent; the body type is configurable
type Event = FsCodec.ITimelineEvent<EventBody>
// Propulsion's Sinks by default use ReadOnlyMemory<byte> as the storage format
and EventBody = ReadOnlyMemory<byte>
// the above Events can be decoded by a Codec implementing this interface
and Codec<'E> = FsCodec.IEventCodec<'E, EventBody, unit>
/// Generates a Codec for the specified Event Union type
let codec<'E when 'E :> TypeShape.UnionContract.IUnionContract> : Codec<'E> =
// Borrowing the Store serdes; frequently the events you parse can use less complex options...
Codec.Create<'E>(serdes = Store.serdes)
// as we know our event bodies are all UTF8 encoded JSON, we can render the string as a log event property
// alternately, you can render the EventBody directly and ensure you have appropriate type destructuring configured
let private render (x: EventBody): string =
FsCodec.Encoding.GetStringUtf8 x
/// Uses the supplied codec to decode the supplied event record `x`
/// (iff at LogEventLevel.Debug, detail fails to `log` citing the `streamName` and body)
let decode<'E> (log: Serilog.ILogger) (codec: Codec<'E>) (streamName: FsCodec.StreamName) (x: Event) =
match codec.Decode x with
| ValueNone ->
if log.IsEnabled Serilog.Events.LogEventLevel.Debug then
log.ForContext("event", render x.Data, true)
.Debug("Codec {type} Could not decode {eventType} in {stream}", codec.GetType().FullName, x.EventType, streamName)
ValueNone
| ValueSome x -> ValueSome x
/// Attempts to decode the supplied Event using the supplied Codec
let [<return: Struct>] (|Decode|_|) (codec: Codec<'E>) struct (streamName, event) =
decode Serilog.Log.Logger codec streamName event
module Array = let inline chooseV f xs = [| for item in xs do match f item with ValueSome v -> yield v | ValueNone -> () |]
/// Yields the subset of events that successfully decoded (could be Array.empty)
let decode<'E> (codec: Codec<'E>) struct (streamName, events: Event[]): 'E[] =
events |> Array.chooseV (decode<'E> Serilog.Log.Logger codec streamName)
let (|Decode|) = decode
If we assume we have the standard module Streams, module Events, and module Stream as above, and the following module Reactions:
module Reactions =
let private dec = Streams.codec<Events.Event>
/// Yields decoded events and relevant strongly typed ids if the Category of the Stream Name matches
let [<return: Struct>] (|Decode|_|) = function
| struct (For clientId, _) & Streams.Decode dec events -> ValueSome struct (clientId, events)
| _ -> ValueNone
let react (clientId: ClientId) (event: Events.Event[]) =
printfn "Client %s, events %A" (ClientId.toString clientId) event
let runCodec () =
for streamName, xs in events |> Seq.groupBy fst do
let events = xs |> Seq.map snd |> Array.ofSeq
match struct (streamName, events) with
| Reactions.Decode (clientId, events) ->
react clientId events
| FsCodec.StreamName.Split (cat, sid), events ->
for e in events do
printfn "Unhandled Event: Category %s, Id %A, Index %d, Event: %A " cat sid e.Index e.EventType
runCodec ()
Normally, the log.IsEnabled call instantly rules out any need for logging.
We can activate this inert logging hook by reconfiguring the logging as follows:
// Switch on debug logging to get detailed information about events that don't match (which has no singificant perf cost when not switched on)
open Serilog
open Serilog.Events
let outputTemplate = "{Message} {Properties}{NewLine}"
Serilog.Log.Logger <-
LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(LogEventLevel.Debug, outputTemplate=outputTemplate)
.CreateLogger()
runCodec ()
This adds the following additional output when triggering runCodec ():-
Codec "<Snipped>" Could not decode "Exported" in "Favorites-ClientB" {event="{ \"count\": 2 }"}
Handling versioning of events in F# with FsCodec
As a system evolves, the types used for events will inevitably undergo changes too. There are thorough guides such as
Versioning in an Event Sourced System by Greg Young; this will only scratch the surface,
with some key F# snippets.
High level rules:
- The most important rule of all is that you never want to relinquish Total Matching, i.e. never add a
_ catch all case
to a match expression.
- The simplest way to add a new field in a backward compatible manner is by adding it as an
option and then using
pattern matching to handle presence or absence of the value.
- Where it becomes impossible to use the serialization-time conversion mechanisms such as
JsonIsomorphism (See example in Propulsion)
the next step is to mint a new Event Type with a different body type. e.g. if we have a Properties, but it becomes
necessary to use a instead PropertiesV2:
type Properties = { a: string }
type PropertiesV2 = { a: string; b: int }
type Event =
| PropertiesUpdated of {| properties: Properties |}
| PropertiesUpdatedV2 of {| properties: PropertiesV2 |}
The migration steps would be:
- update all decision functions to only produce
PropertiesUpdatedV2
- pull out helper functions for pattern matches and do the upconversion inline in the fold
module Fold =
let applyUpdate state (e: PrppertiesV2) = ...
let evolve state = function
| Events.PropertiesUpdated e -> applyUpdate state e
| Events.PropertiesUpdatedV2 e -> applyUpdate state { a = e.a; b = PropertiesV2.defaultB }
Avoiding versioning by optional or nullable fields
The following demonstrates the addition of a CartId property (which is an F# type) in a newer version of CreateCart.
module CartV1 =
type CreateCart = { name: string }
module CartV2Null =
type CreateCart = { name: string; cartId: CartId }
module CartV2Option =
type CreateCart = { name: string; cartId: CartId option }
module CartV2Nullable =
type CreateCart = { name: string; count: Nullable<int> }
While the CartV2Null form can be coerced into working by using Unchecked.defaultof<_> mechanism (or, even worse,
by using the AllowNullLiteral attribute), this is not recommended.
Instead, it's recommended to follow normal F# conventions, wrapping the new field as an option as per CartV2Option.
For Value Types, you could also use Nullable, but option is recommended even for value types, for two reasons:
- it works equally for Value Types (
struct in C#, type [<Struct>] in F#)
and Reference Types (class in C#, type in F#) without requiring different code treatment when switching
- F# has much stronger built-in support for pattern matching and otherwise operation on
options
See the Adding Fields Example for further examples
Upconversion by mapping Event Types
The preceding optional fields mechanism is the recommended default approach for handling versioning of event records.
Of course, there are cases where that becomes insufficient. In such cases, the next level up is to add a new Event Type.
module EventsV0 =
type Properties = { a: string }
type PropertiesV2 = { a: string; b: int }
type Event =
| PropertiesUpdated of {| properties: Properties |}
| PropertiesUpdatedV2 of {| properties: PropertiesV2 |}
In such a situation, you'll frequently be able to express instances of the older event body type in terms of the new one.
For instance, if we had a default (Null object pattern value for b
you can upconvert from one event body to the other, and allow the domain to only concern itself with one of them.