Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

F# Event-Union Contract Encoding with versioning tolerant converters supporting System.Text.Json and Newtonsoft.Json

License

NotificationsYou must be signed in to change notification settings

jet/FsCodec

Repository files navigation

Build StatusreleaseNuGetlicense

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 inapplications leveragingEquinox and/orPropulsion, 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 supportingnetstandard2.1 (F# 4.5+) profiles.

  • Codec NuGetFsCodec 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 ofencode anddecode 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
  • Box Codec NuGetFsCodec.Box: SeeFsCodec.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 withEquinox.MemoryStore
  • Newtonsoft.Json Codec NuGetFsCodec.NewtonsoftJson: As described ina 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 usingTypeShape'sUnionContractEncoder
    • Uses the ubiquitousNewtonsoft.Json library to serialize the event bodies.
    • Provides relevant Converters for common non-primitive types prevalent in F#
    • depends onFsCodec.Box,Newtonsoft.Json >= 13.0.3,Microsoft.IO.RecyclableMemoryStream >= 3.0.0,System.Buffers >= 4.5.1
  • System.Text.Json Codec NuGetFsCodec.SystemTextJson: See#38: drop in replacement that allows one to retarget fromNewtonsoft.Json to the .NET Core >= v 3.0 default serializer:System.Text.Json, solely by changing the referenced namespace.
    • depends onFsCodec.Box,System.Text.Json >= 6.0.1,

Features:FsCodec

The purpose of theFsCodec 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). InheritsIEventData, addingIndex andIsUnfold in order to represent the position on the timeline that the event logically occupies.
  • FsCodec.IEventCodec presentsEncode: 'Context option * 'Event -> IEventData andDecode: ITimelineEvent -> 'Event voption methods that can be used in low level application code to generateIEventDatas or decodeITimelineEvents based on a contract defined by'Union
  • FsCodec.Codec.Create implementsIEventCodec in terms of suppliedencode: 'Event -> string * byte[] anddecode: string * byte[] -> 'Event voption functions (other overloads are available for advanced cases)
  • FsCodec.Core.EventData.Create is a low level helper to create anIEventData directly for purposes such as tests etc.
  • FsCodec.Core.TimelineEvent.Create is a low level helper to create anITimelineEvent 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 eitherNewtonsoft.Json orSystem.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 viaUnionEncoder, orstring values viaTypeSafeEnumConverter)
  • don't surprise .NET developers used toJSON.NET orSystem.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 (althoughSystem.Text.Json v>= 6 does now provide such support)

Codec

FsCodec.NewtonsoftJson/SystemTextJson.Codec provides an implementation ofIEventCodec as described ina 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 usingNewtonsoft.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 therecommendations, 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 aJsonConverterAttribute 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 thetype or property in question. This also aligns well with the notion of cordoning off amodule Events as described inEquinox'smodule Aggregate documentation:types that participate in an Event union are definedand 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 byJsonIsomorphism has resulted in this set alone proving sufficient for two major subsystems of a large e-commerce software suite. Seerecommendations for further expansion on this (TL;DR it does mean ruling out using some type constructs directly in event and/or binding contracts and usingAnti Corruption Layer and/orevent versioning techniques.

... but don't forgetFSharp.SystemTextJson

The role and intention of the converters in the box inFsCodec.SystemTextJson and/orFsCodec.NewtonsoftJson has always been to be minimal but provide escape hatches; short lived shims absolutely fit within this remit. For example, with regard toSystem.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 representationsFsCodec.SystemTextJson can handle in any significant way over time (the advice forFsCodec.NewtonsoftJson has always been to avoid stuff outside of records,options andarrays) - 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 ofSystem.Text.Json Converters is theFSharp.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 relevantConverter/JsonConverter in order to facilitate interoperable and versionable renderings:

  • TypeSafeEnumConverter represents discriminated union (whose cases are all nullary), as astring in a trustworthy manner (Newtonsoft.Json.Converters.StringEnumConverter permits values outside the declared values) 🙏@amjjd

  • UnionConverter represents F# discriminated unions as a single JSONobject 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 byNewtonsoft.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

    NOTESystem.Text.Json, even in v6.0 does not support F# unions out of the box. It's not intended to extend the representationsFsCodec.SystemTextJson can handle in any significant way over time - if you have specific requirements, the powerful and completeFSharp.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 ofJsonIsomorphism 🙏@EirikTsarpalis

Newtonsoft.Json-specific low level converters

  • OptionConverter represents F#'sOption<'t> as a value ornull; included in the standardOptions.Create profile.
  • VerbatimUtf8JsonConverter captures/renders known valid UTF8 JSON data into abyte[] without decomposing it into an object model (not typically relevant for application level code, used inEquinox.Cosmos versions prior to3.0).

System.Text.Json-specific low level converters

  • UnionOrTypeSafeEnumConverterFactory: Global converter that can applyTypeSafeEnumConverter to all Discriminated Unions that do not have cases with values, andUnionConverter to ones that have values. SeethisSystem.Text.Json issue for background information as to the reasoning behind and tradeoffs involved in applying such a policy.
  • RejectNullStringConverter: Global converter that rejectsnull string values, forcing explicit use ofstring option where there is a need to represent anull value

FsCodec.NewtonsoftJson.Options

FsCodec.NewtonsoftJson.Options provides a clean syntax for building aNewtonsoft.Json.JsonSerializerSettings with which to define a serialization contract profile for interoperability purposes. Methods:

  • CreateDefault: as perNewtonsoft.Json defaults with the following override:
    • DateTimeZoneHandling = DateTimeZoneHandling.Utc (default isRoundtripKind)
    • no customIContractResolver (one is expected to usecamelCase field names within records, for which this does not matter)
  • Create: asCreateDefault with the following difference:
    • adds anOptionConverter (seeConverters, above)
  • Default: Default settings; same as callingCreate() produces

FsCodec.SystemTextJson.Options

FsCodec.SystemTextJson.Options provides a clean syntax for building aSystem.Text.Json.Serialization.JsonSerializerOptions as perFsCodec.NewtonsoftJson.Options, above. Methods:

  • CreateDefault: configures the settings equivalent tonew JsonSerializerSettings() orJsonSerializerSettings.Default, without overrides of any kind (seeCreate, below for the relevant differences)
  • Create: asCreateDefault with the following difference:
    • By default, inhibits the HTML-safe escaping thatSystem.Text.Json provides as a default by overridingEncoder withSystem.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
    • (camelCase = true): opts into camel case conversion forPascalCased properties andDictionary keys
    • (autoTypeSafeEnumToJsonString = true): triggers usage ofTypeSafeEnumConverter for any F# Discriminated Unions that only contain nullary cases. SeeAutoUnionTests.fs for examples
    • (autoUnionToJsonObject = true): triggers usage of aUnionConverter to round-trip F# Discriminated Unions (with at least a single case that has a body) as JSON Object structures. SeeAutoUnionTests.fs for examples
    • (rejectNullStrings = true): triggers usage ofRejectNullStringConverter to rejectnull as a value for strings (string option can be used to handle them explicitly).
  • Default: Default settings; same as callingCreate() produces (same intent asJsonSerializerOptions.Default)

Serdes

FsCodec.SystemTextJson/NewtonsoftJson.Serdes provides light wrappers over(JsonConvert|JsonSerializer).(Des|S)erialize(Object)? based on an explicitly supplied serialization profile created byOptions.Create (above), or usingOptions.Default. This enables one to smoothly switch betweenSystem.Text.Json vsNewtonsoft.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 inOptions.Create
  • Deserialize<T>: deserializes an object per its type using the settings defined inOptions.Create
  • Options: Allows one to access theJsonSerializerSettings/JsonSerializerOptions used by this instance.

Usage of Converters with ASP.NET Core

ASP.NET Core's out-of-the-box behavior is to useSystem.Text.Json. One can explicitly opt to useNewtonsoft.Json via theMicrosoft.AspNetCore.Mvc.NewtonsoftJson package'sAddNewtonsoftJson 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 yourmodule Events that you surface while you are scaffolding and/or hacking without an anti-corruption layer) will fall into one of two classifications:

  1. Types that have an associated Converter explicitly annotated (e.g., DU types bear an associatedUnionConverter,TypeSafeEnumConverter orJsonIsomorphism-based custom converter, custom types follow the conventions or define aJsonIsomorphism-based converter)
  2. 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 globalOptionConverter for Newtonsoft, handled intrinsically bySystem.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 withNewtonsoft.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.Defaultservices.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 theserdes serialization/deserialization policy (currently onlyFsCodec.NewtonsoftJson.OptionConverter) into the equivalent managed by ASP.NET.

ASP.NET Core withSystem.Text.Json

The equivalent for the nativeSystem.Text.Json, as of v6, thanksto the great work of the .NET team, is presently a no-op.

The following illustrates how to opt intoautoTypeSafeEnumToJsonString and/orautoUnionToJsonObject modes, andrejectNullStrings 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 converterslet options = FsCodec.SystemTextJson.Options.Create(autoTypeSafeEnumToJsonString = true, autoUnionToJsonObject = true, rejectNullString = true)let serdes = FsCodec.SystemTextJson.Serdes optionsservices.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 intests/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 forFsCodec.SystemTextJson:tests/FsCodec.SystemTextJson.Tests/Examples.fsx.

Examples of usingSerdes 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 necessitatingConverters directly and only records andoptions

The minimal code needed to define helpers to consistently roundtrip where one only uses simple types is to simply state" _Please useFsCodec.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 :-

openFsCodec.SystemTextJson// or FsCodec.NewtonsoftJson if you prefer and/or have legacy converters etcmoduleContract=typeItem={ value:string option}// No special policies required as we are using standard typesletprivateserdes= Serdes Options.Default// implies default settings from Options.Create(), i.e., includes UnsafeRelaxedJsonEscapingletserialize(x:Item):string= serdes.Serialize x// implies default settings from Options.Create()letdeserialize(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 customNewtonsoft.Json.Converter type):

moduleContract=typeItem={ value:string option; other:TypeThatRequiresMyCustomConverter}/// Options to be used within this contract - note the Pascal Cased Value property compared to the previous record definitionletprivateoptions= Options.Create(converters=[| MyCustomConverter()|], camelCase=true)letprivateserdes= Serdes optionsletserialize(x:Item)= serdes.Serialize xletdeserialize(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 asbool,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 anull ornull-equivalent value with the valuenull. This behavior can be overridden viaOptions(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 kindTL;DRNotesExample inputExample output
't[]As per C#Don't forget to handlenull[ 1; 2; 3][1,2,3]
DateTimeOffsetRoundtrips cleanlyThe defaultOptions.Create requestsRoundtripKindDateTimeOffset.Now"2019-09-04T20:30:37.272403+01:00"
Nullable<'t>As per C#;Nullable() ->null,Nullable x ->xOOTB Json.NET and STJ roundtrip cleanly. Works withOptions.CreateDefault(). Worth considering if your contract does not involve manyoption typesNullable 1414
't optionSome null,None ->null,Some x ->xwith the converterOptions.Create() addsOOTB Json.NET does not roundtripoption types cleanly;Options.Create wires in anOptionConverter by default inFsCodec.NewtonsoftJson
NOTESome null will producenull, but deserialize asNone - i.e., it's not round-trippable
Some 1414
stringAs per C#; need to handlenull. Can opt into rejecting null values with(rejectNullStrings = true)One can use astring option to mapnull andSome null toNone"Abc""Abc"
types with unit of measureWorks 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 type54<g>54
FSharp.UMX taggedstring,DateTimeOffsetWorks wellFSharp.UMX enables one to type-tagstring andDateTimeOffset values using the units of measure compiler feature, which Json.NET will render as if they were unadornedSkuId.parse "54-321""000-054-321"
recordsJust workForSystem.Text.Json v4.x, usage of[<CLIMutable>] or a customJsonRecordConverter was once required{| a = 1; b = Some "x" |}"{"a":1,"b":"x"}"
Nullary unions (Enum-like DU's without bodies)Tagtype withTypeSafeEnumConverterWorks well - guarantees a valid mapping, as opposed to using aSystem.Enum andStringEnumConverter, which can map invalid values and/or silently map to0 etcState.NotFound"NotFound"
Discriminated Unions (where one or more cases has a body)Tagtype withUnionConverterThis 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 kindTL;DRExample inputExample outputNotes
't listDon't use; use't[][ 1; 2; 3][1,2,3]While the happy path works,null or missing field maps to anull 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 haveFsCodec.NewtonsoftJson provide support for it in the name of interoperability)
DateTimeDon't use; useDateTimeOffsetRound-tripping can be messy, wrong or lossy;DateTimeOffset covers same use cases
Guid orFSharp.UMX taggedGuiddon't use; wrap as a referencetype and use aJsonIsomorphism, or represent as a taggedstringGuid.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 aJsonIsomorphism. Alternately, represent in your contract as aFSharp.UMX tagged-string.
maps/Dictionary etc.avoid; prefer arraysAs 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
ForSystem.Text.Json, use anIDictionary<'K, 'V> orDictionary<'K, 'V>
tuplesDon'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 asType Safe Enums, especially in Java circles),whatNewtonsoft.Json does forenum values with theStringEnumConverter. This is motivated by the fact that the outof the box behaviors are unsatisfactory for bothNewtonsoft.Json and forSystem.Text.Json (but, for different, unfortunate reasons...).

Out of the box behavior:Newtonsoft.Json

By default, a Nullary Union's default rendering viaNewtonsoft.Json, without any converters in force,is a generic rendering that treats the values as DU values with bodies are treated.

typeStatus= Initial| ActivetypeStatusMessage={ name:string option; status:Status}letstatus={ 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 humanserdes.Serialize status// "{"name":null,"status":{"Case":"Initial"}}"// If we pretty-print it, things get worse, not better:letserdesFormatted= 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:typeStatus= Initial| ActivetypeStatusMessage={ name:string option; status:Status}letstatus={ 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

TheTypeSafeEnumConverter alters this incomplete and/or inconsistent behavior to encode values directly asStringEnumConverter does forenum (System.Enum), for both serializers:

FsCodec.NewtonsoftJson.TypeSafeEnumConverter

ForNewtonsoft.Json, the recommended approach is to tag each Nullary Union Type with aJsonConverter attribute:

letserdes2= Serdes.Default[<Newtonsoft.Json.JsonConverter(typeof<TypeSafeEnumConverter>)>]typeStatus2= Initial| ActivetypeStatusMessage2={ name:string option; status:Status2}letstatus2={ 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:openFsCodec.NewtonsoftJsonletserdesWithConverter= Serdes(Options.Create(TypeSafeEnumConverter()))// NOTE: no JsonConverter attributetypeStatus3= Initial| ActivetypeStatusMessage3={ name:string option; status:Status3}letstatus3={ name= None; status= Initial}serdesWithConverter.Serialize status3// "{"name":null,"status":"Initial"}"

FsCodec.SystemTextJson.TypeSafeEnumConverter<'T>

ForSystem.Text.Json, the process is a little different, as Converters inSystem.Text.Json are expected to work for a single type only.

Using the same type that was rejected by out-of-the-boxSystem.Text.Json earlier:

typeStatus= Initial| ActivetypeStatusMessage={ name:string option; status:Status}letstatus={ name= None; status= Initial}

We can supply a Converter via theOptions:

openFsCodec.SystemTextJsonletserdesWithConverter= Serdes<| Options.Create(TypeSafeEnumConverter<Status>())serdesWithConverter.Serialize status// "{"name":null,"status":"Initial"}"Rather than havingto supply lotsofsuchconverterisntances,therecommendationistotageachtype:```fsharpletserdes= 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>>)>]typeStatus2= Initial| ActivetypeStatusMessage2={ name:string option; status:Status2}letstatus2={ name= None; status= Initial}serdes.Serialize status2

Using theTypeSafeEnumConverter inFsCodec.SystemTextJson, each Nullary Union Type needs it's own converter registered.

openFsCodec.SystemTextJson// NOTE: Every Nullary Union Type needs a specific instantiation of the generic converter registered:letserdesWithConverter= Serdes<| Options.Create(TypeSafeEnumConverter<Status>())serdesWithConverter.Serialize status// "{"name":null,"status":"Initial"}"

The equivalent of registering a single global TypeSafeEnumConverter is theautoTypeSafeEnumToJsonString setting on theOptions:

openFsCodec.SystemTextJsonletoptions= Options.Create(autoTypeSafeEnumToJsonString=true, rejectNullStrings=true)letserdes3= Serdes optionstypeStatus3= Initial| ActivetypeStatusMessage3={ name:string option; status:Status3}letstatus3={ name= None; status= Initial} serdes3.Serialize status3// "{"name":null,"status":"Initial"}"

Custom converters usingJsonIsomorphism

JsonIsomorphism enables one to express theReading andWriteing of the JSON for a type in terms of another type. As alluded to above, rendering and parsing ofGuid 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:

typeGuidConverter()=inherit JsonIsomorphism<Guid, string>()override_.Pickle g= g.ToString"N"override_.UnPickle g= Guid.Parse g

JsonIsomporphism can also be used together withFsCodec.TypeSafeEnum, to deal with mapping of values fromstring to Nullary Unions that don't fit in the easy cases.

[<JsonConverter(typeof<TypeSafeEnumConverter>)>]typeOutcome= Joy| Pain| MiserytypeMessage={ name:string option; outcome:Outcome}letvalue={ name= Somenull; 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 inOutcomeWithOther (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 usingJsonIsomorphism

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>)>]typeOutcomeWithOther= Joy| Pain| Misery| OtherandOutcomeWithCatchAllConverter()=inherit JsonIsomorphism<OutcomeWithOther, string>()override_.Pickle v=        FsCodec.TypeSafeEnum.toString voverride_.UnPickle json=        json|> FsCodec.TypeSafeEnum.tryParse<OutcomeWithOther>|> Option.defaultValue OthertypeMessage2={ name:string option; outcome:OutcomeWithOther}

Because thetype is tagged with a Converter attribute, valid values continue to be converted correctly:

letvalue2={ name= Somenull; 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

Seetests/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 categorytypeIEventCodec<'Event,'Format,'Context>=/// Encodes a 'Event instance into a 'Format representationabstractEncode: context:'Context* value:'Event->IEventData<'Format>/// Decodes a formatted representation into a 'Event instance. Does not throw exception on undefined EventTypesabstractDecode: encoded:ITimelineEvent<'Format>->'Eventvoption

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 aTimeline) - (seeFsCodec.IEventData)
  • decoding event records from an Event Store in aprogramming model, which involves mapping from the source event together with contextual information (seeFsCodec.ITimelineEvent) such as:
    • Theevent 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 coreevent data (often encoded as JSON, protobufs etc), the schema for which typically varies byevent type
    • event metadata (contextual information optionally stored alongside the event)
    • theTimestamp at which the event was generated
    • theIndex 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 versionedsummary 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 eventstypeIEventData<'Format>=/// The Event Type, used to drive deserializationabstractmemberEventType:string/// Event body, as UTF-8 encoded JSON ready to be injected into the StoreabstractmemberData:'Format/// Optional metadata (null, or same as Data, not written if missing)abstractmemberMeta:'Format/// Application-generated identifier used to drive idempotent writes based on deterministic Ids and/or Request IdabstractmemberEventId:System.Guid/// The Correlation Id associated with the flow that generated this event. Can be `null`abstractmemberCorrelationId:string/// The Causation Id associated with the flow that generated this event. Can be `null`abstractmemberCausationId: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.abstractmemberTimestamp:System.DateTimeOffset

Events from a versioned feed and/or being loaded from an Event Store bring additional context beyond the base information inIEventData

/// Represents a Domain Event or Unfold, together with it's 0-based Index in the event sequencetypeITimelineEvent<'Format>=inherit IEventData<'Format>/// The 0-based index into the event sequence of this EventabstractmemberIndex:int64/// Application-supplied context related to the origin of this eventabstractmemberContext: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 IndexabstractmemberIsUnfold:bool

Contracts for parsing / routing event records

Seea scheme for the serializing Events modelled as an F# Discriminated Union for details of the representation scheme used for the events when usingFsCodec.NewtonsoftJson.Codec.Create. We'll use the following example contract for the illustration:

moduleEvents=typeAdded={ item:string}typeRemoved={ name:string}typeEvent=| AddedofAdded| RemovedofRemovedinterface TypeShape.UnionContract.IUnionContractletcodec= Store.codec<Event>

whereStore refers to a set of infrastructure helpers:

namespace globalopenFsCodec.SystemTextJsonmoduleStore=typeEvent= 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 basedandEventBody= ReadOnlyMemory<byte>andCodec<'Ewhen'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 Documentationletprivateoptions= Options.Create(autoTypeSafeEnumToJsonString=true, autoUnionToJsonObject=true)letserdes= Serdes optionsletcodec<'Ewhen'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.

Strongly typed stream ids usingFSharp.UMX

The example event stream contract above uses aClientId type which (while being a string at heart) represents the identifier for a specific entity. We use theFSharp.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.

openFSharp.UMXtype[<Measure>]clientIdtypeClientId= string<clientId>moduleClientId=letparse(str:string):ClientId=% strlettoString(value:ClientId):string=% valuelet(|Parse|)= ClientId.parse

Stream naming conventions

The de-facto standard Event StoreEventStore.org and its documentation codifies the following convention for the naming of streams:-

{Category}-{StreamId}

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; seethe code.

TheStreamName 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 aStreamName. 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>]streamNametypeStreamName= string<streamName>moduleStreamName=lettoString(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 formletparse(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 `-`letcreate(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 '_'letcompose(category:string)(streamIdElements:string[]):StreamName=.../// Extracts the category portion of the StreamNameletcategory(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>letsplit(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 onelettryFind categoryName(x:StreamName):StreamId voption=...

TheStreamId part's key helpers are as follows:

/// Represents the second half of a canonical StreamName, i.e., the streamId in "{categoryName}-{streamId}"typeStreamId= string<streamId>and [<Measure>]streamId/// Helpers for composing and rendering StreamId valuesmodule StreamId=/// Any string can be a StreamId; parse/dec/Elements.split will judge whether it adheres to a valid formletcreate:string->StreamId= UMX.tag/// Render as a string for external uselettoString: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 `_` charsletgen(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 `_` charsletgen2 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 `_` charsletgen3 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 `_` charsletgen4 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 emptyletparseExactlyOne(x:StreamId):string=.../// Validates and extracts the StreamId into a single fragment value/// Throws if the item embeds a `_`, is `null`, or is emptylet(|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.letparse count(x:StreamId):string[]=letxs= Elements.split xif xs.Length<> countthen            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.letdec f(x:StreamId)=                   parseExactlyOne x|> f/// Extracts 2 fragments from the StreamId. Throws if the value does not adhere to that expected form.letdec2 f1 f2(x:StreamId)=letxs= parse2 xinstruct(f1 xs[0], f2 xs[1])/// Extracts 3 fragments from the StreamId. Throws if the value does not adhere to that expected form.letdec3 f1 f2 f3(x:StreamId)=letxs= parse3 xinstruct(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.letdec4 f1 f2 f3 f4(x:StreamId)=letxs= parse4 xinstruct(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 theStreamName/StreamId section above for the underlying interfaces.

(* Stream id generation/parsing logic. Normally kept private; Reactions module exposes relevant parsers to the wider application*)moduleprivateStream=// 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 Idletid: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 Categoryletname: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 formatletdecodeId: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.letdecode:FsCodec.StreamName->ClientId voption= FsCodec.StreamName.tryFind Category>> ValueOption.map decodeIdmoduleReactions=/// 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 matcheslet [<return: Struct>](|For|_|)= Stream.decodeletprivatedec= Streams.codec<Events.Event>/// Yields decoded events and relevant strongly typed ids if the Category of the Stream Name matcheslet [<return: Struct>](|Decode|_|)=function|struct(For clientId,_)& Streams.Decode dec events-> ValueSomestruct(clientId, events)|_-> ValueNone

Decoding events

Given the following example events from across streams:

letutf8(s:string)= System.Text.Encoding.UTF8.GetBytes(s)letstreamForClient c= Stream.name(ClientId.parse c)letevents=[    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" }""")]andthe 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> bodiestype Event= FsCodec.ITimelineEvent<EventBody>andEventBody= ReadOnlyMemory<byte>andCodec<'E>= FsCodec.IEventCodec<'E, EventBody, unit>letstreamCodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>:Codec<'E>=    Codec.Create<'E>(serdes= Store.serdes)letdec= streamCodec<Events.Event>let [<return:Struct>](|DecodeEvent|_|)(codec:Codec<'E>)event= codec.Decode eventletrunCodecExplicit()=for stream, eventin eventsdomatch stream, eventwith| Reactions.For clientId, DecodeEvent dec e->            printfn $"Client%s{ClientId.toString clientId}, event%A{e}"| FsCodec.StreamName.Splitstruct(cat, sid), e->            printfn $"Unhandled Event: Category%s{cat}, Ids%s{FsCodec.StreamId.toString sid}, Index%d{e.Index}, Event:%A{e.EventType}"

TheReactions.For clientId bit above is the inverse of theStream.name function. It parses aStreamNameback to the the application-level identifiers (theClientId type), _but only if theCategorypart of the name matches (i.e., thestream nameStartsWith("Favorites-")). While this may seemlike a lot of busywork, it pays off when you have multiple stream categories, each with different identifiers (orcases 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)

invokingrunCodecExplicit () 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:

  1. "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
  2. "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 asUnhandled 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. SeeLogging 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 :-

moduleReactionsBasic=letdec= 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:

letreactSingle(clientId:ClientId)(event:Events.Event)=    printfn $"Client%s{ClientId.toString clientId}, event%A{event}"letrunCodecMatch()=for streamName, eventin eventsdomatch streamName, eventwith| 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 theSerilog library), can be used to selectively layer on some logging when run with logging upped toDebug level:

moduleStreams=// Events coming from streams are carried as a TimelineEvent; the body type is configurabletypeEvent= FsCodec.ITimelineEvent<EventBody>// Propulsion's Sinks by default use ReadOnlyMemory<byte> as the storage formatandEventBody= ReadOnlyMemory<byte>// the above Events can be decoded by a Codec implementing this interfaceandCodec<'E>= FsCodec.IEventCodec<'E, EventBody, unit>/// Generates a Codec for the specified Event Union typeletcodec<'Ewhen'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 configuredletprivaterender(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)letdecode<'E>(log:Serilog.ILogger)(codec:Codec<'E>)(streamName:FsCodec.StreamName)(x:Event)=match codec.Decode xwith| ValueNone->if log.IsEnabled Serilog.Events.LogEventLevel.Debugthen                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 Codeclet [<return: Struct>](|Decode|_|)(codec:Codec<'E>)struct(streamName,event)=        decode Serilog.Log.Logger codec streamName eventmoduleArray=let inlinechooseV f xs=[|for itemin xsdomatch f itemwith ValueSome v->yield v| ValueNone->()|]/// Yields the subset of events that successfully decoded (could be Array.empty)letdecode<'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 standardmodule Streams,module Events, andmodule Stream as above, and the followingmodule 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.EventTyperunCodec ()

Normally, thelog.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)openSerilogopenSerilog.EventsletoutputTemplate="{Message} {Properties}{NewLine}"Serilog.Log.Logger<-    LoggerConfiguration()        .MinimumLevel.Debug()        .WriteTo.Console(LogEventLevel.Debug, outputTemplate=outputTemplate)        .CreateLogger()runCodec()

This adds the following additional output when triggeringrunCodec ():-

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 asVersioning in an Event Sourced System by Greg Young; this will only scratch the surface,with some key F# snippets.

High level rules:

  1. The most important rule of all is that you never want to relinquish Total Matching, i.e. never add a_ catch all caseto a match expression.
  2. The simplest way to add a new field in a backward compatible manner is by adding it as anoption and then usingpattern matching to handle presence or absence of the value.
  3. Where it becomes impossible to use the serialization-time conversion mechanisms such asJsonIsomorphism (See example in Propulsion)the next step is to mint a new Event Type with a different body type. e.g. if we have aProperties, but it becomesnecessary to use a insteadPropertiesV2:
    typeProperties={ a:string}typePropertiesV2={ a:string; b:int}typeEvent=| PropertiesUpdatedof{| properties: Properties|}| PropertiesUpdatedV2of{| properties: PropertiesV2|}
    The migration steps would be:
    • update all decision functions to only producePropertiesUpdatedV2
    • pull out helper functions for pattern matches and do the upconversion inline in the fold
      moduleFold=letapplyUpdate state(e:PrppertiesV2)=...letevolve 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 aCartId property (which is an F#type) in a newer version ofCreateCart.

moduleCartV1=typeCreateCart={ name:string}moduleCartV2Null=typeCreateCart={ name:string; cartId:CartId}moduleCartV2Option=typeCreateCart={ name:string; cartId:CartId option}moduleCartV2Nullable=typeCreateCart={ name:string; count:Nullable<int>}

While theCartV2Null form can be coerced into working by usingUnchecked.defaultof<_> mechanism (or, even worse,by using theAllowNullLiteral attribute), this is not recommended.

Instead, it's recommended to follow normal F# conventions, wrapping the new field as anoption as perCartV2Option.

For Value Types, you could also useNullable, butoption 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 onoptions

See theAdding Fields Example for further examples

Upconversion by mapping Event Types

The precedingoptional 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.

moduleEventsV0=typeProperties={ a:string}typePropertiesV2={ a:string; b:int}typeEvent=| PropertiesUpdatedof{| properties: Properties|}| PropertiesUpdatedV2of{| 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 forbyou can upconvert from one event body to the other, and allow the domain to only concern itself with one of them.

moduleEventsUpDown=typeProperties={ a:string}typePropertiesV2={ a:string; b:int}modulePropertiesV2=letdefaultB=2/// The possible representations within the store[<RequireQualifiedAccess>]typeContract=| PropertiesUpdatedof{| properties: Properties|}| PropertiesUpdatedV2of{| properties: PropertiesV2|}interface TypeShape.UnionContract.IUnionContract/// Used in the model - all decisions and folds are in terms of thistypeEvent=| PropertiesUpdatedof{| properties: PropertiesV2|}letup:Contract->Event=function| Contract.PropertiesUpdated e-> PropertiesUpdated{| properties={ a= e.properties.a; b= PropertiesV2.defaultB}|}| Contract.PropertiesUpdatedV2 e-> PropertiesUpdated eletdown:Event->Contract=function| Event.PropertiesUpdated e-> Contract.PropertiesUpdatedV2 eletcodec= Codec.Create<Event, Contract,_>(up=(fun _e c-> up c),                                                     down=fun e->struct(down e, ValueNone, ValueNone))moduleFold=typeState= unit// evolve functionsletevolve state=function| EventsUpDown.Event.PropertiesUpdated e-> state

The main weakness of such a solution is that theupconvert anddownconvert functions can get long (if your Event Types list is long).

See theUpconversion example.

Upconversion via Active Patterns

Here are some techniques that can be used to bridge the gap if you don't go with full upconversion from aContract DU type to a Domain one.

moduleEvents=typeProperties={ a:string}typePropertiesV2={ a:string; b:int}modulePropertiesV2=letdefaultB=2typeEvent=| PropertiesUpdatedof{| properties: Properties|}| PropertiesUpdatedV2of{| properties: PropertiesV2|}let(|Updated|)=function| PropertiesUpdated e->{| properties={ a= e.properties.a; b= PropertiesV2.defaultB}|}| PropertiesUpdatedV2 e-> emoduleFold=typeState={ b:int}letevolve state:Events.Event->State=function| Events.Updated e->{ statewith b= e.properties.b}

The main reason this is not a universal solution is that such Active Patterns are currently limited to 7 cases.

See theUpconversion active patterns.

Adding metadata to events based on Domain-intrinsic information

The following recipe can be used to populate theMeta field of an event based on information your application supplies within Events it generates:

moduleStoreWithMeta=typeEvent<'E>= int64* Metadata* 'EandMetadata={ principal:string}andCodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>= FsCodec.IEventCodec<Event<'E>, Store.EventBody, unit>// no special requirements for deserializing Metadata, so use Default Serdesletprivateserdes= Serdes.Defaultletcodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>:Codec<'E>=// here we surface the metadata from the raw event as part of the application level event based on the stored formletup(raw:Store.Event)(contract:'E):Event<'E>=            raw.Index, serdes.Deserialize<Metadata> raw.Meta, contract// _index: up and down are expected to encode/decode symmetrically - when encoding, the app supplies a dummy, and the store assigns it on appending// the metadata is encoded as the normal bodies areletdown((_index,meta:Metadata,event:'E):Event<'E>)=struct(event, ValueSome meta, ValueNone)        Codec.Create<Event<'E>, 'E, Metadata>(up, down, serdes= Store.serdes)

The above embeds and/or extracts contextual information from the Event'sMeta field.

NOTE this works well as long as the information in question is generated naturally as part of the application's processing,and it is relevant in the context of all operations within a Service.Where this is not the case (e.g., if you are attempting to add out of band contextual causation/correlation information thatis external to the application's logic, see [Context](#context].

Adding Metadata to Events based on extrinsic Context

In the section ongenerating Metadata based on domain information, we were able to generate metadata for the eventbased solely on information within the application level event. That's not frequently possible; normally, such informationis not required as part of the requirements of the application logic generating the Events. While one could of course passsuch information down the layers all the way to where the application level event is being generated in order to facilitate it'sinclusion, that'll typically be messy (and in many cases, producing an event is not always necessary).

The typical example of such a requirement is where one wishes to decorate events with metadata based on some ambient contextsuch as the hosting infrastructure-supplied Correlation and Causation Identifiers or similar.

Of course, it can sometimes be possible to grab those from a Logical Call Context etc - where that makes sense, you can simplyapply theStoreWithMeta recipe. However, that makes codecs much harder to test, especially if the causation mapping is complexand/or you want to test that it's being executed correctly.

In such cases, one can supply a'Context to theIEventCodec when requesting an application event beEncoded.That relevant'Context is in turn made available to amapCausation function at the point where anIEventDatais being produced.

The following is an example of a Codec employing themapCausation facility to implement such behavior:

moduleStoreWithContext=typeContext={ correlationId:string; causationId:string; principal:string}andCodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>= FsCodec.IEventCodec<'E, Store.EventBody, Context voption>andMetadata={ principal:string}letcodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>:Codec<'E>=letup(_raw:Store.Event)(contract:'E)= contractletdown(event:'E)=// Not producing any Metadata based on the application-level event in this instanceletmeta= ValueNone: Metadata voptionletts= ValueNonestruct(event, meta, ts)letmapCausation(context:Context voption)(_downConvertedMeta:Metadata voption)=leteventId= Guid.NewGuid()letmetadata,corrId,causeId=match contextwith| ValueNone->// In some parts of this system, we don't have a Context to pass - hence we use `Context voption`// as the context type in this instance. Generally, it's recommended for this mapping function// to throw in order to have each path in the system that wishes to generate events be required// to supply the relevant attribution information. But, here we illustrate how to do it loosey goosey!                    ValueNone,null,null| ValueSome v->// We map the correlation/causation identifiers into the designated fields// the remaining information, we save into the Event's Meta field// In this instance, we don't have any metadata arising from the application level events,//   but, if we did, we could merge it into the final rendered `ValueSome` we are passing downletfinalMeta={ principal= v.principal}                    ValueSome finalMeta, v.correlationId, v.causationIdstruct(metadata, eventId, corrId, causeId)        Codec.Create<'E, 'E, Metadata, Context voption>(up, down, mapCausation, serdes= Store.serdes)

An example of how that facility is used in practice is viaEquinox'scontextargument forDecider.createWithContext; whenever an event is being encoded to go into the store, the relevant'Context is supplied to the Codec, which percolates through to themapCausation function above.

Given an application infrastructure type such as

typeExternalContext(applicationRelevantThing,correlationId,causationId,principal)=member_.ApplicationRelevantThing= applicationRelevantThingmember_.StoreContext:StoreWithContext.Context={   correlationId= correlationId            causationId= causationId            principal= principal}

The application logic can utilise it like this:

moduleFavoritesmoduleEvents=typeEvent=| Add| Removeinterface TypeShape.UnionContract.IUnionContractletcodec= StoreWithContext.codec<Event>moduleFold=typeState=...letdecide appRelevantThing command:Event list=...typeService(resolve: StoreWithContext.Context*ClientId->Decider<Events.Event, Fold.State>)=member_.Handle(context:ExternalContext,clientId,request)=letdecider= resolve(context.StoreContext, clientId)        decider.Transact(decide context.ApplicationRelevantThing command)moduleFactory=letcreate store=letcategory:Equinox.Category<..>=Cosmos.createcodec...letresolve=Store.createDecidercontextcategoryService(resolve)

In the above, ifdecide produces events, themapCausation function gets to generate the Metadata as required.

Then, in an outer layer, it gets passed through like this:

letstore= Store.connect...letservice= Favorites.Factory.create store...letctx= ExternalContext(...)letclientId,request=...service.Handle(ctx, clientId, request)

Parsing Metadata from Events arriving via Streams

Events arriving from a store (e.g. Equinox etc) or source (e.g. Propulsion) often bear contextual metadata(this may have been added viadomain-level Metadata, orextrinsic contextual Metadata).

Where relevant, a decoding process may want to surface such context alongside mapping the base information.

A clean way to wrap such a set of transitions is as follows:

We simulate a set of events on the Stream, with attached metadata, decorating the standard events as follows:

leteventsWithMeta=seq{for sn, ein events->letmeta= utf8"""{"principal": "me"}"""    sn, FsCodec.Core.TimelineEvent.Create(e.Index, e.EventType, e.Data, meta)}

Then, we have a standard helper module, which wraps the decoding of the data, extracting the relevant information:

moduleStreamsWithMeta=typeEvent<'E>=(struct(int64* Metadata* 'E))andMetadata={ principal:string}andCodec<'E>= FsCodec.IEventCodec<Event<'E>, Streams.EventBody, unit>// no special requirements for deserializing metadata, so use Default Serdesletprivateserdes= Serdes.Defaultletcodec<'Ewhen'E:>TypeShape.UnionContract.IUnionContract>:Codec<'E>=// here we surface some metadata from the raw event as part of the application level typeletup(raw:Streams.Event)(contract:'E):Event<'E>=struct(raw.Index, serdes.Deserialize<Metadata> raw.Meta, contract)// We are not using this codec to encode events, so we let the encoding side fail very fastletdown _= failwith"N/A"        Codec.Create<Event<'E>, 'E, Metadata>(up, down, options= Store.options)|> FsCodec.Encoder.Uncompressed

Then, per the relevant Event contract, we define a Decode pattern to decode relevant events from the stream, if this event is relevant for us:

module ReactionsWithMeta =         let dec = StreamsWithMeta.codec<Events.Event>    let [<return: Struct>] (|Decode|_|) = function        | struct (Reactions.For clientId, _) & Streams.Decode dec events -> ValueSome struct (clientId, events)        | _ -> ValueNone

With the above, we can then handle batches of events for a stream as delivered without any parsing logic mixed in:

letreactStreamWithMeta(clientId:ClientId)(events:StreamsWithMeta.Event<Events.Event>[])=for index, meta, eventin eventsdo        printfn $"Client%s{ClientId.toString clientId}, event%i{index} meta%A{meta} event%A{event}"lethandleWithMeta streamName events=matchstruct(streamName, events)with| ReactionsWithMeta.Decode(clientId, events)->        reactStreamWithMeta clientId events| FsCodec.StreamName.Split(cat, sid),_->for ein eventsdo        printfn $"Unhandled Event: Category%s{cat}, Id%A{sid}, Index%d{e.Index}, Event:%s{e.EventType}"

We can now dispatch as follows:

letrunStreamsWithMeta()=for streamName, xsin eventsWithMeta|> Seq.groupBy fstdoletevents= xs|> Seq.map snd|> Array.ofSeq        handleWithMeta streamName events        runStreamsWithMeta()

yielding the following output:

Client ClientA index 0 time 2020-01-13 09:44:37Z event Added {item = "a";}Client ClientB index 0 time 2020-01-13 09:44:37Z event Added {item = "b";}Client ClientA index 1 time 2020-01-13 09:44:37Z event Added {item = "b";}Client ClientB index 1 time 2020-01-13 09:44:37Z event Added {item = "a";}Client ClientB index 2 time 2020-01-13 09:44:37Z event Removed {name = null;}Codec "<Snipped>" Could not decode "Exported" in "Favorites-ClientB" {event="{ \"count\": 2 }"}Unhandled Event: Category Favorites, Id ClientB, Index 3, Event: "Exported"Unhandled Event: Category Misc, Id x, Index 0, Event: "Dummy"

Features:FsCodec.Box.Codec

FsCodec.Box.Codec is a drop-in-equivalent forFsCodec.(Newtonsoft|SystemText)Json.Codec with equivalent.Create overloads that encode asITimelineEvent<obj> (as opposed toITimelineEvent<ReadOnlyMemory<byte>> /ITimelineEvent<JsonElement>).

This is useful when storing events in aMemoryStore as it allows one to take the perf cost and ancillary yak shaving induced by round-tripping arbitrary event payloads to the concrete serialization format out of the picture when writing property based unit and integration tests.

NOTE this does not imply one should avoid testing this aspect; the opposite in fact -- one should apply theTest Pyramid principles:

  • have a focused series of tests that validate that the various data representations in the event bodies are round-trippablea. in the chosen encoding format (i.e. UTF8 JSON)b. with the selected concrete json encoder (i.e.Newtonsoft.Json for now 🙁)
  • integration tests can in general useBoxEncoder andMemoryStore

You should absolutely have acceptance tests that apply the actual serialization encoding with the real store for a representative number of scenarios at the top of the pyramid

RELATED ARTICLES / BLOG POSTS etc

CONTRIBUTING

The intention is to keep this set of converters minimal and interoperable, e.g., many candidates are deliberately being excluded from this set;its definitely a non-goal for this to become a compendium of every possible converter.So, especially in this repo, the bar for adding converters will be exceedingly high and hence any contribution should definitely be preceded by a discussion.

Examples, tests and docs are welcomed with open arms.

General guidelines:

  • Less [converters] is more -has a converterreally proved itself broadly applicable ?
  • this is not the final complete set of converters; Json.NET and System.Text.Json are purposefully extensible and limited only by your imagination, for better or worse. However such specific conversions are best kept within the app.
  • If the upstream library (Newtonsoft.Json,System.Text.Json) can or should be made to do something, it should. Also forSystem.Text.Json, if it's an F#-specific, the powerful and completeFSharp.SystemTextJson library may be much more aligned.

Please raise GitHub issues for any questions so others can benefit from the discussion.

Building

# verify the integrity of the repo wrt being able to build/pack/test./dotnet build build.proj

[8]ページ先頭

©2009-2025 Movatter.jp