├── Components.PNG ├── Generated.png ├── .nuget ├── NuGet.exe ├── NuGet.Config └── NuGet.targets ├── StateMachine.PNG ├── Encapsulation.PNG ├── Statemachine.vsdx ├── RfqStateMachine ├── Service │ ├── IQuote.cs │ ├── IQuoteRequest.cs │ ├── IExecutionReport.cs │ ├── IExecutionRequest.cs │ └── IRfqService.cs ├── RfqState.cs ├── Utils │ └── IConcurrencyService.cs ├── IRfq.cs ├── RfqEvent.cs ├── packages.config ├── RfqUpdate.cs ├── Properties │ └── AssemblyInfo.cs ├── RfqStateMachine.csproj └── Rfq.cs ├── Tests ├── StateMachineExtensions.cs ├── TestDoubles │ ├── ConcurrencyServiceDouble.cs │ └── RfqServiceDouble.cs ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── StateMachineDiagramPrinter.cs ├── RfqStateMachineTests.cs └── Tests.csproj ├── RfqStateMachine.sln ├── .gitignore ├── LICENSE ├── README.md └── README.html /Components.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/Components.PNG -------------------------------------------------------------------------------- /Generated.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/Generated.png -------------------------------------------------------------------------------- /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/.nuget/NuGet.exe -------------------------------------------------------------------------------- /StateMachine.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/StateMachine.PNG -------------------------------------------------------------------------------- /Encapsulation.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/Encapsulation.PNG -------------------------------------------------------------------------------- /Statemachine.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/HEAD/Statemachine.vsdx -------------------------------------------------------------------------------- /RfqStateMachine/Service/IQuote.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine.Service 2 | { 3 | public interface IQuote 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /RfqStateMachine/Service/IQuoteRequest.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine.Service 2 | { 3 | public interface IQuoteRequest 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /RfqStateMachine/Service/IExecutionReport.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine.Service 2 | { 3 | public interface IExecutionReport 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /RfqStateMachine/Service/IExecutionRequest.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine.Service 2 | { 3 | public interface IExecutionRequest 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /RfqStateMachine/RfqState.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine 2 | { 3 | public enum RfqState 4 | { 5 | Input, 6 | Requesting, 7 | Cancelling, 8 | Cancelled, 9 | Quoted, 10 | Executing, 11 | Error, 12 | Done 13 | } 14 | } -------------------------------------------------------------------------------- /RfqStateMachine/Utils/IConcurrencyService.cs: -------------------------------------------------------------------------------- 1 | using System.Reactive.Concurrency; 2 | 3 | namespace RfqStateMachine.Utils 4 | { 5 | public interface IConcurrencyService 6 | { 7 | IScheduler Dispatcher { get; } 8 | IScheduler TaskPool { get; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /RfqStateMachine/IRfq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using RfqStateMachine.Service; 3 | 4 | namespace RfqStateMachine 5 | { 6 | public interface IRfq : IDisposable 7 | { 8 | void RequestQuote(IQuoteRequest quoteRequest); 9 | void Cancel(long rfqId); 10 | void Execute(IExecutionRequest quote); 11 | 12 | IObservable Updates { get; } 13 | } 14 | } -------------------------------------------------------------------------------- /RfqStateMachine/Service/IRfqService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reactive; 3 | 4 | namespace RfqStateMachine.Service 5 | { 6 | public interface IRfqService 7 | { 8 | IObservable RequestQuoteStream(IQuoteRequest quoteRequest); 9 | IObservable Execute(IExecutionRequest executionRequest); 10 | IObservable Cancel(long rfqId); 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/StateMachineExtensions.cs: -------------------------------------------------------------------------------- 1 | using Stateless; 2 | 3 | namespace Tests 4 | { 5 | public static class StateMachineExtensions 6 | { 7 | public static string ToStateDiagram(this StateMachine stateMachine) 8 | { 9 | var printer = new StateMachineDiagramPrinter(stateMachine); 10 | return printer.ToDiagram(); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /RfqStateMachine/RfqEvent.cs: -------------------------------------------------------------------------------- 1 | namespace RfqStateMachine 2 | { 3 | public enum RfqEvent 4 | { 5 | UserRequests, 6 | UserCancels, 7 | UserExecutes, 8 | 9 | ServerNewQuote, 10 | ServerQuoteError, 11 | ServerQuoteStreamComplete, 12 | ServerSendsExecutionReport, 13 | ServerExecutionError, 14 | ServerCancelled, 15 | ServerCancellationError, 16 | 17 | InternalError, 18 | } 19 | } -------------------------------------------------------------------------------- /RfqStateMachine/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Tests/TestDoubles/ConcurrencyServiceDouble.cs: -------------------------------------------------------------------------------- 1 | using System.Reactive.Concurrency; 2 | using RfqStateMachine.Utils; 3 | 4 | namespace Tests.TestDoubles 5 | { 6 | public class ConcurrencyServiceDouble : IConcurrencyService 7 | { 8 | public ConcurrencyServiceDouble() 9 | { 10 | Dispatcher = ImmediateScheduler.Instance; 11 | TaskPool = ImmediateScheduler.Instance; 12 | } 13 | 14 | public IScheduler Dispatcher { get; private set; } 15 | public IScheduler TaskPool { get; private set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RfqStateMachine/RfqUpdate.cs: -------------------------------------------------------------------------------- 1 | using RfqStateMachine.Service; 2 | 3 | namespace RfqStateMachine 4 | { 5 | public class RfqUpdate 6 | { 7 | public RfqState RfqState { get; private set; } 8 | public IQuote Quote { get; private set; } 9 | public IExecutionReport ExecutionReport { get; private set; } 10 | 11 | public RfqUpdate(RfqState rfqState, IQuote quote, IExecutionReport executionReport) 12 | { 13 | RfqState = rfqState; 14 | Quote = quote; 15 | ExecutionReport = executionReport; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Tests/TestDoubles/RfqServiceDouble.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reactive; 3 | using System.Reactive.Subjects; 4 | using RfqStateMachine.Service; 5 | 6 | namespace Tests.TestDoubles 7 | { 8 | public class RfqServiceDouble : IRfqService 9 | { 10 | public RfqServiceDouble() 11 | { 12 | RequestQuoteSubject = new Subject(); 13 | ExecuteSubject = new Subject(); 14 | CancelSubject = new Subject(); 15 | } 16 | 17 | public ISubject RequestQuoteSubject { get; private set; } 18 | public ISubject ExecuteSubject { get; private set; } 19 | public ISubject CancelSubject { get; private set; } 20 | 21 | public IObservable RequestQuoteStream(IQuoteRequest quoteRequest) 22 | { 23 | return RequestQuoteSubject; 24 | } 25 | 26 | public IObservable Execute(IExecutionRequest executionRequest) 27 | { 28 | return ExecuteSubject; 29 | } 30 | 31 | public IObservable Cancel(long rfqId) 32 | { 33 | return CancelSubject; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("95c85320-672e-46ce-b411-93004fbe8218")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /RfqStateMachine/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RfqStateMachine")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("RfqStateMachine")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("be94dc3e-3587-4754-a330-475e0492dd5e")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /RfqStateMachine.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.30324.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RfqStateMachine", "RfqStateMachine\RfqStateMachine.csproj", "{A56556E4-4295-4102-8077-3CEC75722F92}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{2A3B5524-68AD-4B10-A890-1A5DB7843C1B}" 11 | ProjectSection(SolutionItems) = preProject 12 | .nuget\NuGet.Config = .nuget\NuGet.Config 13 | .nuget\NuGet.exe = .nuget\NuGet.exe 14 | .nuget\NuGet.targets = .nuget\NuGet.targets 15 | EndProjectSection 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C24A67E7-24D8-4433-9412-62129ECF2AF5}" 18 | ProjectSection(SolutionItems) = preProject 19 | README.md = README.md 20 | EndProjectSection 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {A56556E4-4295-4102-8077-3CEC75722F92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {A56556E4-4295-4102-8077-3CEC75722F92}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {A56556E4-4295-4102-8077-3CEC75722F92}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {A56556E4-4295-4102-8077-3CEC75722F92}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | EndGlobal 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | bld/ 16 | [Bb]in/ 17 | [Oo]bj/ 18 | 19 | # MSTest test Results 20 | [Tt]est[Rr]esult*/ 21 | [Bb]uild[Ll]og.* 22 | 23 | #NUNIT 24 | *.VisualState.xml 25 | TestResult.xml 26 | 27 | # Build Results of an ATL Project 28 | [Dd]ebugPS/ 29 | [Rr]eleasePS/ 30 | dlldata.c 31 | 32 | *_i.c 33 | *_p.c 34 | *_i.h 35 | *.ilk 36 | *.meta 37 | *.obj 38 | *.pch 39 | *.pdb 40 | *.pgc 41 | *.pgd 42 | *.rsp 43 | *.sbr 44 | *.tlb 45 | *.tli 46 | *.tlh 47 | *.tmp 48 | *.tmp_proj 49 | *.log 50 | *.vspscc 51 | *.vssscc 52 | .builds 53 | *.pidb 54 | *.svclog 55 | *.scc 56 | 57 | # Chutzpah Test files 58 | _Chutzpah* 59 | 60 | # Visual C++ cache files 61 | ipch/ 62 | *.aps 63 | *.ncb 64 | *.opensdf 65 | *.sdf 66 | *.cachefile 67 | 68 | # Visual Studio profiler 69 | *.psess 70 | *.vsp 71 | *.vspx 72 | 73 | # TFS 2012 Local Workspace 74 | $tf/ 75 | 76 | # Guidance Automation Toolkit 77 | *.gpState 78 | 79 | # ReSharper is a .NET coding add-in 80 | _ReSharper*/ 81 | *.[Rr]e[Ss]harper 82 | *.DotSettings.user 83 | 84 | # JustCode is a .NET coding addin-in 85 | .JustCode 86 | 87 | # TeamCity is a build add-in 88 | _TeamCity* 89 | 90 | # DotCover is a Code Coverage Tool 91 | *.dotCover 92 | 93 | # NCrunch 94 | *.ncrunch* 95 | _NCrunch_* 96 | .*crunch*.local.xml 97 | 98 | # MightyMoose 99 | *.mm.* 100 | AutoTest.Net/ 101 | 102 | # Web workbench (sass) 103 | .sass-cache/ 104 | 105 | # Installshield output folder 106 | [Ee]xpress/ 107 | 108 | # DocProject is a documentation generator add-in 109 | DocProject/buildhelp/ 110 | DocProject/Help/*.HxT 111 | DocProject/Help/*.HxC 112 | DocProject/Help/*.hhc 113 | DocProject/Help/*.hhk 114 | DocProject/Help/*.hhp 115 | DocProject/Help/Html2 116 | DocProject/Help/html 117 | 118 | # Click-Once directory 119 | publish/ 120 | 121 | # Publish Web Output 122 | *.[Pp]ublish.xml 123 | *.azurePubxml 124 | 125 | # NuGet Packages Directory 126 | packages/ 127 | ## TODO: If the tool you use requires repositories.config uncomment the next line 128 | #!packages/repositories.config 129 | 130 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 131 | # This line needs to be after the ignore of the build folder (and the packages folder if the line above has been uncommented) 132 | !packages/build/ 133 | 134 | # Windows Azure Build Output 135 | csx/ 136 | *.build.csdef 137 | 138 | # Windows Store app package directory 139 | AppPackages/ 140 | 141 | # Others 142 | sql/ 143 | *.Cache 144 | ClientBin/ 145 | [Ss]tyle[Cc]op.* 146 | ~$* 147 | *~ 148 | *.dbmdl 149 | *.dbproj.schemaview 150 | *.pfx 151 | *.publishsettings 152 | node_modules/ 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | *.mdf 166 | *.ldf 167 | 168 | # Business Intelligence projects 169 | *.rdl.data 170 | *.bim.layout 171 | *.bim_*.settings 172 | 173 | # Microsoft Fakes 174 | FakesAssemblies/ 175 | -------------------------------------------------------------------------------- /Tests/StateMachineDiagramPrinter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using Stateless; 6 | 7 | namespace Tests 8 | { 9 | public class StateMachineDiagramPrinter 10 | { 11 | private const string FullTemplate = @"digraph g{{ 12 | {0} 13 | 14 | {1} 15 | }}"; 16 | 17 | private readonly StateMachine _stateMachine; 18 | 19 | public StateMachineDiagramPrinter(StateMachine stateMachine) 20 | { 21 | _stateMachine = stateMachine; 22 | } 23 | 24 | public string ToDiagram() 25 | { 26 | var stateConfigField = _stateMachine.GetType().GetField("_stateConfiguration", BindingFlags.Instance | BindingFlags.NonPublic); 27 | 28 | var stateConfig = stateConfigField.GetValue(_stateMachine) as IEnumerable; 29 | 30 | var results = IterateStates(stateConfig).ToList(); 31 | 32 | var allStates = results.SelectMany(t => new[] {t.From, t.To}).Distinct().Select(t => t.ToString()); 33 | 34 | return string.Format(FullTemplate, ToString(allStates), ToString(results)); 35 | 36 | } 37 | 38 | private IEnumerable IterateStates(IEnumerable stateConfig) 39 | { 40 | foreach (object o in stateConfig) 41 | { 42 | var fromState = (TState) GetPublicProperty(o, "Key"); 43 | 44 | var value = GetPublicProperty(o, "Value"); 45 | 46 | var triggersField = (IEnumerable) GetPrivateField(value, "_triggerBehaviours"); 47 | 48 | foreach (var trigger in triggersField) 49 | { 50 | var triggerValue = (TTrigger) GetPublicProperty(trigger, "Key"); 51 | var triggerValues = (IEnumerable) GetPublicProperty(trigger, "Value"); 52 | 53 | foreach (var transitionValue in triggerValues) 54 | { 55 | var toState = (TState) GetPrivateField(transitionValue, "_destination"); 56 | 57 | yield return new Transition(fromState, triggerValue, toState); 58 | } 59 | } 60 | } 61 | } 62 | 63 | private object GetPublicProperty(object source, string propertyName) 64 | { 65 | var property = source.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); 66 | return property.GetValue(source); 67 | } 68 | 69 | private object GetPrivateField(object source, string fieldName) 70 | { 71 | var field = source.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); 72 | return field.GetValue(source); 73 | } 74 | 75 | private static string ToString(IEnumerable states) 76 | { 77 | return string.Join(";\n", states) + ";\nnode[shape=plaintext]"; 78 | } 79 | 80 | private static string ToString(IEnumerable transitions) 81 | { 82 | return string.Join("\n", transitions.Select(t => string.Format("{0} -> {2} [label={1}]", t.From, t.Trigger, t.To))); 83 | } 84 | 85 | private class Transition 86 | { 87 | public TState From { get; private set; } 88 | public TTrigger Trigger { get; private set; } 89 | public TState To { get; private set; } 90 | 91 | public Transition(TState @from, TTrigger transition, TState to) 92 | { 93 | From = @from; 94 | Trigger = transition; 95 | To = to; 96 | } 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /RfqStateMachine/RfqStateMachine.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A56556E4-4295-4102-8077-3CEC75722F92} 8 | Library 9 | Properties 10 | RfqStateMachine 11 | RfqStateMachine 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\Stateless.2.4.0\lib\Stateless.dll 37 | 38 | 39 | 40 | 41 | ..\packages\Rx-Core.2.2.4\lib\net45\System.Reactive.Core.dll 42 | 43 | 44 | ..\packages\Rx-Interfaces.2.2.4\lib\net45\System.Reactive.Interfaces.dll 45 | 46 | 47 | ..\packages\Rx-Linq.2.2.4\lib\net45\System.Reactive.Linq.dll 48 | 49 | 50 | ..\packages\Rx-PlatformServices.2.2.4\lib\net45\System.Reactive.PlatformServices.dll 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 80 | 81 | 82 | 83 | 90 | -------------------------------------------------------------------------------- /Tests/RfqStateMachineTests.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Reactive; 5 | using System.Reflection; 6 | using NUnit.Framework; 7 | using RfqStateMachine; 8 | using Stateless; 9 | using Tests.TestDoubles; 10 | 11 | namespace Tests 12 | { 13 | [TestFixture] 14 | public class RfqStateMachineTests 15 | { 16 | private RfqServiceDouble _rfqServiceDouble; 17 | private ConcurrencyServiceDouble _concurrencyServiceDouble; 18 | private IRfq _sut; 19 | private List _updates; 20 | private Exception _error; 21 | private bool _completed; 22 | 23 | [SetUp] 24 | public void SetUp() 25 | { 26 | _rfqServiceDouble = new RfqServiceDouble(); 27 | _concurrencyServiceDouble = new ConcurrencyServiceDouble(); 28 | _sut = new Rfq(_rfqServiceDouble, _concurrencyServiceDouble); 29 | _updates = new List(); 30 | _error = null; 31 | _completed = false; 32 | 33 | _sut.Updates.Subscribe( 34 | _updates.Add, 35 | ex => _error = ex, 36 | () => _completed = true); 37 | } 38 | 39 | [Test] 40 | public void HappyPathScenario() 41 | { 42 | // user request quote 43 | _sut.RequestQuote(null); 44 | // server sends quote 45 | _rfqServiceDouble.RequestQuoteSubject.OnNext(null); 46 | // user executes 47 | _sut.Execute(null); 48 | // server sends execution report 49 | _rfqServiceDouble.ExecuteSubject.OnNext(null); 50 | 51 | Assert.AreEqual(5, _updates.Count); 52 | Assert.AreEqual(RfqState.Input, _updates[0].RfqState); 53 | Assert.AreEqual(RfqState.Requesting, _updates[1].RfqState); 54 | Assert.AreEqual(RfqState.Quoted, _updates[2].RfqState); 55 | Assert.AreEqual(RfqState.Executing, _updates[3].RfqState); 56 | Assert.AreEqual(RfqState.Done, _updates[4].RfqState); 57 | } 58 | 59 | [Test] 60 | public void MultipleServerQuotes() 61 | { 62 | // user request quote 63 | _sut.RequestQuote(null); 64 | // server sends quotes 65 | _rfqServiceDouble.RequestQuoteSubject.OnNext(null); 66 | _rfqServiceDouble.RequestQuoteSubject.OnNext(null); 67 | 68 | Assert.AreEqual(4, _updates.Count); 69 | Assert.AreEqual(RfqState.Input, _updates[0].RfqState); 70 | Assert.AreEqual(RfqState.Requesting, _updates[1].RfqState); 71 | Assert.AreEqual(RfqState.Quoted, _updates[2].RfqState); 72 | Assert.AreEqual(RfqState.Quoted, _updates[3].RfqState); 73 | } 74 | 75 | [Test] 76 | public void UserCancelRequest() 77 | { 78 | // user request quote 79 | _sut.RequestQuote(null); 80 | // user cancels 81 | _sut.Cancel(32); 82 | // server acks 83 | _rfqServiceDouble.CancelSubject.OnNext(Unit.Default); 84 | 85 | Assert.AreEqual(4, _updates.Count); 86 | Assert.AreEqual(RfqState.Input, _updates[0].RfqState); 87 | Assert.AreEqual(RfqState.Requesting, _updates[1].RfqState); 88 | Assert.AreEqual(RfqState.Cancelling, _updates[2].RfqState); 89 | Assert.AreEqual(RfqState.Cancelled, _updates[3].RfqState); 90 | } 91 | 92 | [Test] 93 | public void UserCancelQuote() 94 | { 95 | // user request quote 96 | _sut.RequestQuote(null); 97 | // server sends quotes 98 | _rfqServiceDouble.RequestQuoteSubject.OnNext(null); 99 | // user cancels 100 | _sut.Cancel(32); 101 | // server acks 102 | _rfqServiceDouble.CancelSubject.OnNext(Unit.Default); 103 | 104 | Assert.AreEqual(5, _updates.Count); 105 | Assert.AreEqual(RfqState.Input, _updates[0].RfqState); 106 | Assert.AreEqual(RfqState.Requesting, _updates[1].RfqState); 107 | Assert.AreEqual(RfqState.Quoted, _updates[2].RfqState); 108 | Assert.AreEqual(RfqState.Cancelling, _updates[3].RfqState); 109 | Assert.AreEqual(RfqState.Cancelled, _updates[4].RfqState); 110 | } 111 | 112 | [Test] 113 | public void GenerateStateDiagram() 114 | { 115 | var field = _sut.GetType().GetField("_stateMachine", BindingFlags.Instance | BindingFlags.NonPublic); 116 | var stateMachine = (StateMachine) field.GetValue(_sut); 117 | Console.WriteLine(stateMachine.ToStateDiagram()); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /Tests/Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7F2B7AA1-9EB6-4CB5-8E3D-9F51AA4F9AA0} 8 | Library 9 | Properties 10 | Tests 11 | Tests 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\NUnit.2.6.3\lib\nunit.framework.dll 37 | 38 | 39 | False 40 | ..\packages\Stateless.2.4.0\lib\Stateless.dll 41 | 42 | 43 | 44 | 45 | ..\packages\Rx-Core.2.2.4\lib\net45\System.Reactive.Core.dll 46 | 47 | 48 | ..\packages\Rx-Interfaces.2.2.4\lib\net45\System.Reactive.Interfaces.dll 49 | 50 | 51 | ..\packages\Rx-Linq.2.2.4\lib\net45\System.Reactive.Linq.dll 52 | 53 | 54 | ..\packages\Rx-PlatformServices.2.2.4\lib\net45\System.Reactive.PlatformServices.dll 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | {A56556E4-4295-4102-8077-3CEC75722F92} 76 | RfqStateMachine 77 | 78 | 79 | 80 | 81 | 82 | 83 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 84 | 85 | 86 | 87 | 94 | -------------------------------------------------------------------------------- /.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | false 8 | 9 | 10 | false 11 | 12 | 13 | true 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 31 | 32 | 33 | 34 | 35 | $(SolutionDir).nuget 36 | 37 | 38 | 39 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config 40 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config 41 | 42 | 43 | 44 | $(MSBuildProjectDirectory)\packages.config 45 | $(PackagesProjectConfig) 46 | 47 | 48 | 49 | 50 | $(NuGetToolsPath)\NuGet.exe 51 | @(PackageSource) 52 | 53 | "$(NuGetExePath)" 54 | mono --runtime=v4.0.30319 "$(NuGetExePath)" 55 | 56 | $(TargetDir.Trim('\\')) 57 | 58 | -RequireConsent 59 | -NonInteractive 60 | 61 | "$(SolutionDir) " 62 | "$(SolutionDir)" 63 | 64 | 65 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) 66 | $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols 67 | 68 | 69 | 70 | RestorePackages; 71 | $(BuildDependsOn); 72 | 73 | 74 | 75 | 76 | $(BuildDependsOn); 77 | BuildPackage; 78 | 79 | 80 | 81 | 82 | 83 | 84 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 99 | 100 | 103 | 104 | 105 | 106 | 108 | 109 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /RfqStateMachine/Rfq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reactive.Disposables; 3 | using System.Reactive.Linq; 4 | using System.Reactive.Subjects; 5 | using RfqStateMachine.Service; 6 | using RfqStateMachine.Utils; 7 | using Stateless; 8 | 9 | namespace RfqStateMachine 10 | { 11 | public class Rfq : IRfq 12 | { 13 | private readonly IRfqService _rfqService; 14 | private readonly IConcurrencyService _concurrencyService; 15 | private readonly StateMachine _stateMachine; 16 | private readonly ISubject _rfqUpdateSubject; 17 | private readonly SerialDisposable _requestSubscription = new SerialDisposable(); 18 | private readonly SerialDisposable _cancellationSubscription = new SerialDisposable(); 19 | private readonly SerialDisposable _executionSubscription = new SerialDisposable(); 20 | private readonly CompositeDisposable _disposables; 21 | 22 | // strongly typed triggers (events) 23 | private StateMachine.TriggerWithParameters _rfqEventServerSendsQuote; 24 | private StateMachine.TriggerWithParameters _rfqEventServerSendsExecutionReport; 25 | private StateMachine.TriggerWithParameters _rfqEventUserRequests; 26 | private StateMachine.TriggerWithParameters _rfqEventUserExecutes; 27 | private StateMachine.TriggerWithParameters _rfqEventUserCancels; 28 | private StateMachine.TriggerWithParameters _rfqEventServerQuoteError; 29 | private StateMachine.TriggerWithParameters _rfqEventServerCancellationError; 30 | private StateMachine.TriggerWithParameters _rfqEventServerExecutionError; 31 | 32 | public Rfq(IRfqService rfqService, IConcurrencyService concurrencyService) 33 | { 34 | _rfqService = rfqService; 35 | _concurrencyService = concurrencyService; 36 | _stateMachine = new StateMachine(RfqState.Input); 37 | _rfqUpdateSubject = new BehaviorSubject(new RfqUpdate(RfqState.Input, null, null)); 38 | _disposables = new CompositeDisposable(_cancellationSubscription, _executionSubscription, _requestSubscription); 39 | 40 | CreateStateMachine(); 41 | } 42 | 43 | /* ---------------------------------------- 44 | * PUBLIC API 45 | * 46 | * /!\ Only statemachine transitions allowed here /!\ 47 | * 48 | * ---------------------------------------*/ 49 | 50 | public void RequestQuote(IQuoteRequest quoteRequest) 51 | { 52 | _stateMachine.Fire(_rfqEventUserRequests, quoteRequest); 53 | } 54 | 55 | public void Cancel(long rfqId) 56 | { 57 | _stateMachine.Fire(_rfqEventUserCancels, rfqId); 58 | } 59 | 60 | public void Execute(IExecutionRequest executionRequest) 61 | { 62 | _stateMachine.Fire(_rfqEventUserExecutes, executionRequest); 63 | } 64 | 65 | public IObservable Updates { get { return _rfqUpdateSubject; } } 66 | 67 | /* ---------------------------------------- 68 | * STATEMACHINE DEFINITION 69 | * ---------------------------------------*/ 70 | 71 | private void CreateStateMachine() 72 | { 73 | // define strongly typed triggers (events) 74 | _rfqEventServerSendsQuote = _stateMachine.SetTriggerParameters(RfqEvent.ServerNewQuote); 75 | _rfqEventServerSendsExecutionReport = _stateMachine.SetTriggerParameters(RfqEvent.ServerSendsExecutionReport); 76 | _rfqEventServerQuoteError = _stateMachine.SetTriggerParameters(RfqEvent.ServerQuoteError); 77 | _rfqEventServerCancellationError = _stateMachine.SetTriggerParameters(RfqEvent.ServerCancellationError); 78 | _rfqEventServerExecutionError = _stateMachine.SetTriggerParameters(RfqEvent.ServerExecutionError); 79 | _rfqEventUserRequests = _stateMachine.SetTriggerParameters(RfqEvent.UserRequests); 80 | _rfqEventUserExecutes = _stateMachine.SetTriggerParameters(RfqEvent.UserExecutes); 81 | _rfqEventUserCancels = _stateMachine.SetTriggerParameters(RfqEvent.UserCancels); 82 | 83 | _stateMachine.OnUnhandledTrigger(OnUnhandledTrigger); 84 | 85 | _stateMachine.Configure(RfqState.Input) 86 | .OnEntry(LogTransition) 87 | .Permit(RfqEvent.UserRequests, RfqState.Requesting); 88 | 89 | _stateMachine.Configure(RfqState.Requesting) 90 | .OnEntry(LogTransition) 91 | .OnEntryFrom(_rfqEventUserRequests, OnEntryRequesting) 92 | .Permit(RfqEvent.ServerNewQuote, RfqState.Quoted) 93 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 94 | .Permit(RfqEvent.InternalError, RfqState.Error); 95 | 96 | _stateMachine.Configure(RfqState.Quoted) 97 | .OnEntry(LogTransition) 98 | .OnEntryFrom(_rfqEventServerSendsQuote, OnEntryQuoted) 99 | .PermitReentry(RfqEvent.ServerNewQuote) 100 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 101 | .Permit(RfqEvent.UserExecutes, RfqState.Executing) 102 | .OnExit(OnExitQuoted); 103 | 104 | _stateMachine.Configure(RfqState.Executing) 105 | .OnEntry(LogTransition) 106 | .OnEntryFrom(_rfqEventUserExecutes, OnEntryExecuting) 107 | .Permit(RfqEvent.ServerSendsExecutionReport, RfqState.Done); 108 | 109 | _stateMachine.Configure(RfqState.Cancelling) 110 | .OnEntry(LogTransition) 111 | .OnEntryFrom(_rfqEventUserCancels, OnEntryCancelling) 112 | .Permit(RfqEvent.ServerCancelled, RfqState.Cancelled); 113 | 114 | _stateMachine.Configure(RfqState.Cancelled) 115 | .OnEntry(LogTransition) 116 | .OnEntry(OnEntryCancelled); 117 | 118 | _stateMachine.Configure(RfqState.Done) 119 | .OnEntry(LogTransition) 120 | .OnEntryFrom(_rfqEventServerSendsExecutionReport, OnEntryDone); 121 | 122 | _stateMachine.Configure(RfqState.Error) 123 | .OnEntry(LogTransition) 124 | .OnEntryFrom(_rfqEventServerQuoteError, OnEntryError) 125 | .OnEntryFrom(_rfqEventServerExecutionError, OnEntryError); 126 | } 127 | 128 | /* ---------------------------------------- 129 | * STATEMACHINE TRANSITION HANDLERS 130 | * 131 | * All internal logic should be handled here. 132 | * For server calls, server callbacks (ie. responses, errors, etc) 133 | * are only allowed to transition the state machine 134 | * ---------------------------------------*/ 135 | 136 | private void OnEntryQuoted(IQuote quote) 137 | { 138 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Quoted, quote, null)); 139 | } 140 | 141 | private void OnEntryRequesting(IQuoteRequest quoteRequest) 142 | { 143 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Requesting, null, null)); 144 | 145 | _requestSubscription.Disposable = _rfqService.RequestQuoteStream(quoteRequest) 146 | .Timeout(TimeSpan.FromSeconds(5)) 147 | .ObserveOn(_concurrencyService.Dispatcher) 148 | .SubscribeOn(_concurrencyService.TaskPool) 149 | .Subscribe( 150 | // /!\ we are only allowed to transition the state machine here, no other code! 151 | // This applies to all server callbacks 152 | quote => _stateMachine.Fire(_rfqEventServerSendsQuote, quote), 153 | ex => _stateMachine.Fire(_rfqEventServerQuoteError, ex), 154 | () => _stateMachine.Fire(RfqEvent.ServerQuoteStreamComplete)); 155 | } 156 | 157 | private void OnEntryCancelling(long rfqId, StateMachine.Transition transition) 158 | { 159 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Cancelling, null, null)); 160 | 161 | _cancellationSubscription.Disposable = _rfqService.Cancel(rfqId) 162 | .Timeout(TimeSpan.FromSeconds(5)) 163 | .ObserveOn(_concurrencyService.Dispatcher) 164 | .SubscribeOn(_concurrencyService.TaskPool) 165 | .Subscribe( 166 | // /!\ we are only allowed to transition the state machine here, no other code! 167 | // This applies to all server callbacks 168 | _ => _stateMachine.Fire(RfqEvent.ServerCancelled), 169 | ex => _stateMachine.Fire(_rfqEventServerCancellationError, ex)); 170 | } 171 | 172 | private void OnEntryExecuting(IExecutionRequest executionRequest) 173 | { 174 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Executing, null, null)); 175 | 176 | _executionSubscription.Disposable = _rfqService.Execute(executionRequest) 177 | .Timeout(TimeSpan.FromSeconds(5)) 178 | .ObserveOn(_concurrencyService.Dispatcher) 179 | .SubscribeOn(_concurrencyService.TaskPool) 180 | .Subscribe( 181 | // /!\ we are only allowed to transition the state machine here, no other code! 182 | // This applies to all server callbacks 183 | executionReport => _stateMachine.Fire(_rfqEventServerSendsExecutionReport, executionReport), 184 | ex => _stateMachine.Fire(_rfqEventServerExecutionError, ex)); 185 | } 186 | 187 | private void OnExitQuoted() 188 | { 189 | // we no longer need the quote stream, unsubscribe 190 | _requestSubscription.Dispose(); 191 | } 192 | 193 | private void OnEntryDone(IExecutionReport executionReport) 194 | { 195 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Done, null, executionReport)); 196 | } 197 | 198 | private void OnEntryCancelled(StateMachine.Transition transition) 199 | { 200 | _rfqUpdateSubject.OnNext(new RfqUpdate(RfqState.Cancelled, null, null)); 201 | _rfqUpdateSubject.OnCompleted(); 202 | } 203 | 204 | private void OnEntryError(Exception ex) 205 | { 206 | _rfqUpdateSubject.OnError(ex); 207 | } 208 | 209 | /* ---------------------------------------- 210 | * INTERNAL STUFF 211 | * ---------------------------------------*/ 212 | 213 | private void LogTransition(StateMachine.Transition transition) 214 | { 215 | Console.WriteLine("[Event {0}] {1} --> {2}", transition.Trigger, transition.Source, transition.Destination); 216 | } 217 | 218 | private void OnUnhandledTrigger(RfqState state, RfqEvent trigger) 219 | { 220 | var message = string.Format("State machine received an invalid trigger '{0}' in state '{1}'", trigger, state); 221 | Console.WriteLine(message); 222 | 223 | _rfqUpdateSubject.OnError(new ApplicationException(message)); 224 | } 225 | 226 | public void Dispose() 227 | { 228 | _disposables.Dispose(); 229 | } 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RFQ State Machine 2 | 3 | We highlighted quite a few techniques to deal with reactive systems in [Reactive Trader](https://github.com/AdaptiveConsulting/ReactiveTrader). There is another one, that we commonly use, that was not demonstrated. 4 | A *state machine* is a simple yet powerful way of decomposing some functionality into *states* and a set of valid *transitions* between them. 5 | When you find yourself dealing for instance with user input and/or server events and see lots of branching in your code (if/switch statements) on some `_state` variables, chances are high that a state machine could be introduced to simplify things. 6 | 7 | In this post we will look at a concrete use case, we will define a state machine for it and we will see how we can organise our code around the state machine and interact with it. I've also created a [companion GitHub project](https://github.com/AdaptiveConsulting/RfqStateMachine) where you can find the 8 | full example. 9 | 10 | ## Example: RFQ workflow 11 | 12 | In finance "Request for Quote" (RFQ) is a common mechanism used to request a price electronically: the client submits a request to the pricing server. 13 | At some point the server provides a quote (or a series of quotes) and the client can decide to execute (hit) or pass (cancel). When a client "executes" or "hits" a price they are actually placing an Order to make a trade at that given price. This order could still be rejected for reasons that could be 14 | * financial (client has exceed their credit limit), 15 | * environmental (excessive latency) or 16 | * market driven (large move in the market means all trades are off). 17 | 18 | We are going to build a state machine that would live client side, in some UI application like [reactive trader](https://github.com/AdaptiveConsulting/ReactiveTrader), to control the state of an RFQ. 19 | 20 | The following diagram describes the different states of the RFQ and the possible transitions. 21 | 22 | ![state machine diagram](https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/master/StateMachine.PNG?token=1256913__eyJzY29wZSI6IlJhd0Jsb2I6QWRhcHRpdmVDb25zdWx0aW5nL1JmcVN0YXRlTWFjaGluZS9tYXN0ZXIvU3RhdGVNYWNoaW5lLlBORyIsImV4cGlyZXMiOjE0MDQwMzI4NDN9--33bd8eef1b0c9c1064f9d1844ed8f99cb19b96b4) 23 | 24 | This is a visual representation of a state machine, it contains 25 | 26 | - states: 27 | - an initial state (at the top), 28 | - intermediate states (requesting, quoted, Executing) 29 | - terminal states (Error, Done, Cancelled) 30 | - and transitions between states (arrows) 31 | 32 | I find those diagrams very helpful to think about the system, while building them I will generally go through all the states I already discovered and ask myself the following questions: 33 | 34 | - Could anything else happen in this state? 35 | - Are there any unhappy paths? (e.g. time-outs, error, etc.) 36 | - Do we have a representation of this particular state in the UI? (if you are building a UI). 37 | 38 | Those diagrams are also very useful to discuss with non developers: business people, UX, etc. 39 | 40 | ## From diagram to code 41 | 42 | State machines can be implemented in many different ways, either from scratch or using some library. 43 | For any decent size state machine I tend to use [Stateless](https://code.google.com/p/stateless/) but the recommendations that follow would stand for any library or hand written state machine. 44 | 45 | I like to define state machines in a single place: I find that spreading the definition across multiple files/classes makes it harder to understand. 46 | 47 | _Stateless_ offers a nice fluent syntax to define states and possible transitions. 48 | 49 | ###Defining states 50 | 51 | 52 | The first thing we need to do is to define the set of states, we can use an enum for that: 53 | 54 | ```csharp 55 | public enum RfqState 56 | { 57 | Input, 58 | Requesting, 59 | Cancelling, 60 | Cancelled, 61 | Quoted, 62 | Executing, 63 | Error, 64 | Done 65 | } 66 | ``` 67 | [gist](https://gist.github.com/odeheurles/9160c1b3e0687d3ebf38#file-rfqstates) 68 | 69 | ###Events 70 | 71 | Then we define the events which will trigger transitions between states. In our case those are events coming from the client or from the server. 72 | 73 | Again we can use an enum to define those events. 74 | 75 | 76 | ```csharp 77 | public enum RfqEvent 78 | { 79 | UserRequests, 80 | UserCancels, 81 | UserExecutes, 82 | 83 | ServerNewQuote, 84 | ServerQuoteError, 85 | ServerQuoteStreamComplete, 86 | ServerSendsExecutionReport, 87 | ServerExecutionError, 88 | ServerCancelled, 89 | ServerCancellationError, 90 | 91 | InternalError, 92 | } 93 | ``` 94 | [gist](https://gist.github.com/odeheurles/14bbd2a0b8040a808356#file-rfqevent) 95 | 96 | I like to prefix those events with their origin, just to makes things explicit (here we have 'Server', 'User', 'Internal') 97 | 98 | As you can see events coming from the server always expose a happy path (for instance `ServerNewQuote` when the server sends a new quote) and at least one corresponding error event (`ServerQuoteError`). 99 | 100 | ![Components](https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/master/Components.PNG?token=1256913__eyJzY29wZSI6IlJhd0Jsb2I6QWRhcHRpdmVDb25zdWx0aW5nL1JmcVN0YXRlTWFjaGluZS9tYXN0ZXIvQ29tcG9uZW50cy5QTkciLCJleHBpcmVzIjoxNDA0MDMyOTYxfQ%3D%3D--f635d386ef4ee480652de98f62d9903fc2660e25) 101 | 102 | 103 | You will also often have internal events, for instance a timer expiring can raise an internal event to trigger a state transition. 104 | 105 | Events may or not carry some data: for instance `UserRequests` event needs to contain the description of the product being priced. 106 | For those events requiring parameters it is useful to define strongly typed events. 107 | 108 | This is how we declare them with _Stateless_, for instance for the `ServerSendsQuote` event: 109 | 110 | ```csharp 111 | _rfqEventServerSendsQuote = _stateMachine.SetTriggerParameters(RfqEvent.ServerNewQuote); 112 | ``` 113 | [gist](https://gist.github.com/odeheurles/dea91fa626e6b468ef07#file-stronglytypedevent) 114 | 115 | ###Defining transitions 116 | 117 | Now we can define transitions. For each state we define which events are allowed and when they are triggered to which state we will transition. 118 | This is very straight forward with stateless: 119 | 120 | ```csharp 121 | _stateMachine.Configure(RfqState.Input) 122 | .Permit(RfqEvent.UserRequests, RfqState.Requesting); 123 | 124 | _stateMachine.Configure(RfqState.Requesting) 125 | .Permit(RfqEvent.ServerNewQuote, RfqState.Quoted) 126 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 127 | .Permit(RfqEvent.InternalError, RfqState.Error); 128 | 129 | _stateMachine.Configure(RfqState.Quoted) 130 | .PermitReentry(RfqEvent.ServerNewQuote) 131 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 132 | .Permit(RfqEvent.UserExecutes, RfqState.Executing); 133 | 134 | _stateMachine.Configure(RfqState.Executing) 135 | .Permit(RfqEvent.ServerSendsExecutionReport, RfqState.Done); 136 | 137 | _stateMachine.Configure(RfqState.Cancelling) 138 | .Permit(RfqEvent.ServerCancelled, RfqState.Cancelled); 139 | ``` 140 | [gist](https://gist.github.com/odeheurles/2a0ef6112f33d9f2425d) 141 | 142 | ### Triggering events 143 | 144 | When the user performs an action or the server sends back a message we want to fire an event at the state machine. 145 | This is straight forward with stateless 146 | 147 | ```csharp 148 | // for an event without parameters 149 | _stateMachine.Fire(RfqEvent.ServerQuoteStreamComplete) 150 | 151 | // for a strongly typed event 152 | _stateMachine.Fire(_rfqEventServerSendsExecutionReport, executionReport) 153 | ``` 154 | [gist](https://gist.github.com/odeheurles/35dae01a47b3d807b97c) 155 | 156 | ###Defining actions 157 | 158 | When we send an event to the state machine, two things can happen, the current state has a valid transition for this event or not. 159 | 160 | If the current state can accept an event we generally want to execute our code at some point around the transition: 161 | 162 | - when you enter a state (or re-enter a state since it's also possible to have transitions looping back on the same state) 163 | - when you exit a state 164 | - upon transition, if you have different behavior to implement for different transitions leading to a same state 165 | 166 | I tend to apply actions upon entry into a state and use the other variants only in specific scenarios. 167 | 168 | **Important: when implementing a statemachine, you want to put all your logic inside those actions (on state entry, on state exit, on transition) because the state machine has already checked that the incoming event was valid for the current state.** 169 | 170 | Here is an example with _Stateless_ syntax. When the user requests a quote we want to log the transition and also to perform some logic on entry in the requesting state: 171 | 172 | ```csharp 173 | _stateMachine.Configure(RfqState.Requesting) 174 | .OnEntry(LogTransition) 175 | .OnEntryFrom(_rfqEventUserRequests, OnEntryRequesting) 176 | .Permit(RfqEvent.ServerNewQuote, RfqState.Quoted) 177 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 178 | .Permit(RfqEvent.InternalError, RfqState.Error); 179 | 180 | private void OnEntryRequesting(IQuoteRequest quoteRequest) 181 | { 182 | // here goes the code to send a quote request to the server 183 | } 184 | ``` 185 | [gist](https://gist.github.com/odeheurles/fce8fdb029501f754df4) 186 | 187 | **Tip**: you can think of the `OnExit` action as a `Dispose()` method for the corresponding state. It is very useful if for instance you had a timer running during that state and you need to cancel it. This also works well with Rx and disposal of subscriptions. 188 | 189 | ### Handling errors 190 | 191 | When an event is fired at the state machine and the state machine has no transition defined for this event in the current state we can implement 2 behaviors: ignoring the event or raising an exception. 192 | 193 | By default _Stateless_ will raise an exception but you can handle yourself invalid transitions: 194 | 195 | ```csharp 196 | _stateMachine.OnUnhandledTrigger(OnUnhandledTrigger); 197 | 198 | private void OnUnhandledTrigger(RfqState state, RfqEvent trigger) 199 | { 200 | var message = string.Format("State machine received an invalid trigger '{0}' in state '{1}'", trigger, state); 201 | Console.WriteLine(message); 202 | 203 | _rfqUpdateSubject.OnError(new ApplicationException(message)); 204 | } 205 | ``` 206 | [gist](https://gist.github.com/odeheurles/a0f838e4b83e53f88379) 207 | 208 | You can also ignore individual events on a state with the Stateless `.Ignore()` method. 209 | 210 | ### Encapsulation 211 | 212 | We have now defined everything we need for the state machine: 213 | - states, 214 | - strongly typed events 215 | - possible transitions 216 | - entry actions 217 | - exit action 218 | - error handling 219 | - how to fire events at the state machine 220 | 221 | The next step is to encapsulate everything in a single class so we don't leak the specifics of _Stateless_ and the state machine to the rest of our code. 222 | 223 | For our example I've created a class _Rfq_ that you can find [here](https://github.com/AdaptiveConsulting/RfqStateMachine/blob/master/RfqStateMachine/Rfq.cs). 224 | 225 | This class implements the following interface: 226 | 227 | ```csharp 228 | public interface IRfq : IDisposable 229 | { 230 | void RequestQuote(IQuoteRequest quoteRequest); 231 | void Cancel(long rfqId); 232 | void Execute(IExecutionRequest quote); 233 | 234 | IObservable Updates { get; } 235 | } 236 | ``` 237 | [gist](https://gist.github.com/odeheurles/911258d648ceb3f1eaba) 238 | 239 | This is very much CQRS style: a view model can call the `RequestQuote`, `Cancel` and `Execute` methods which act as commands and internally fire events. Don't get confused by 'Command' and 'Event', they are the same, it's just that in the context of CQRS we talk about commands and for state machine I've use the term event from the beginning (we could use message as well if we want). 240 | 241 | The view model also subscribes to the Updates stream which will notify when the state machine transitions and provide the relevant data (a quote, an execution report, etc). 242 | 243 | You can find some sample usage of this API in the [test project](https://github.com/AdaptiveConsulting/RfqStateMachine/blob/master/Tests/RfqStateMachineTests.cs). 244 | 245 | ![Encapsulation](https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/master/Encapsulation.PNG?token=1256913__eyJzY29wZSI6IlJhd0Jsb2I6QWRhcHRpdmVDb25zdWx0aW5nL1JmcVN0YXRlTWFjaGluZS9tYXN0ZXIvRW5jYXBzdWxhdGlvbi5QTkciLCJleHBpcmVzIjoxNDA0MTMyMzkwfQ%3D%3D--33adc46c203e50b1adbb54dcdbc27c98faf1d0be) 246 | 247 | ### Concurrency 248 | 249 | I would strongly suggest to get your state machine running on a single thread. In my example the view model OK call from the UI thread (Dispatcher) and I explicitly marshal server side initiated messages to the UI thread using `ObserveOn` in my Rx queries. 250 | 251 | If you are not building a UI you should consider running your state machine in an actor or an event loop: anything that will guarantee that calls made on the state machine are sequenced/serialized and do not have to be synchronized. 252 | 253 | Why? Simply because otherwise you will have to synchronise all accesses to the state machine (and other states in your encapsulating class) with locks. If for instance you take a lock while firing an event, all the actions will run under that lock. Those actions will likely call on code external to this class and you now have risks of deadlock. 254 | 255 | ### Race conditions 256 | 257 | Never forget that in an event driven system things can happen in an order you do not expect, and your state machine should be ready for that. 258 | 259 | Here is an example, which use a slightly different protocol for the RFQ: 260 | 261 | - the user receives a valid quote Q1 from the server 262 | - the server sends an invalid quote message (to invalidate the quote because the market has moved or for whatever reason) 263 | - the user Hit the quote Q1 (executes) while the invalidation message is still in flight (ie. still travelling somewhere between the server and the client) 264 | - the state machine transitions to the state 'Executing' 265 | - the client receives the invalidate quote message/event but the state machine is in a state where you might not have expected to receive such event... 266 | 267 | Because there is a propagation delay between a client and a server, you will see behaviours in your systems that you did not consider initially and that you have probably not covered in your unit tests. 268 | 269 | What to do about it? 270 | 271 | 1. For each state go through the list of all possible events and ask yourself: could this one possibly happen in this state? If it does, how should it be handled? 272 | 2. Log all transitions of the state machine and all events fired. This is priceless while investigating for such issues. 273 | 3. Unit testing is not enough, you will need to test in a deployed environment. 274 | 275 | ### Visualisation 276 | 277 | [Matt](http://weareadaptive.com/author/matt/) wrote [some code](https://github.com/AdaptiveConsulting/RfqStateMachine/blob/master/Tests/StateMachineDiagramPrinter.cs) which reflectively retrieves the definition of the state machine and is able to produce a graph definition in [DOT code](http://www.graphviz.org/doc/info/lang.html) (a language to represent graphs). 278 | 279 | To generate a diagram from the output of the graph generation code, you can either download [Graphviz](http://www.graphviz.org/) and run it locally, or simply use an [online GraphViz webapp](http://sandbox.kidstrythisathome.com/erdos/). 280 | 281 | This is the output I got using the webapp: 282 | 283 | ![Generated diagram](https://raw.githubusercontent.com/AdaptiveConsulting/RfqStateMachine/master/Generated.png) 284 | 285 | ## Wrap up 286 | 287 | It takes a bit of time to get your head around state machines but once you get it those little things yield very nice clean code and it's also very simple to introduce new state and transitions if you follow the few guidelines we discussed here. 288 | 289 | There are a few other things I'd like to talk about with state machines (for instance visualising them while the system is running, code generation, etc) but we will cover that in a future blog post. 290 | 291 | I would also suggest to have a look to the work of Pieter Hintjens (ZeroMQ) on state machines and code generation, he has done some [very cool stuff in this area](https://github.com/zeromq/zproto) -------------------------------------------------------------------------------- /README.html: -------------------------------------------------------------------------------- 1 |

RFQ State Machine

2 | 3 |

We highlighted quite a few techniques to deal with reactive systems in Reactive Trader. There is another one, that we commonly use, that was not demonstrated. 4 | A state machine is a simple yet powerfull way of decomposing some functionality into states and a set of valid transitions between them. 5 | When you find yourself dealing for instance with user input and/or server events and see lots of branching in your code (if/switch statements) on some _state variables, chances are high that a statemachine could be introduced to simplify things.

6 | 7 |

In this post we will look at a concreate usecase, we will define a state machine for it and we will see how we can organise our code around the state machnine and interact with it. I've also created a companion GitHub project where you can find the 8 | full example.

9 | 10 |

Example: RFQ workflow

11 | 12 |

In finance Request For Quote (RFQ) is a common mechanism used to request a price electronically: the client submits a request to the pricing server. 13 | At some point the server provides a quote (or a serie of quotes) and the client can decide to execute (HIT the price) or pass (cancel). 14 | We are going to build a state machine that would live client side, in some UI application like reactive trader, to control the state of a RFQ.

15 | 16 |

The following diagram describes the different states of the RFQ and the possible transitions.

17 | 18 |

state machine diagram

19 | 20 |

This is a visual representation of a statemachine, it contains

21 | 22 |
    23 |
  • states: 24 |
      25 |
    • an initial state (at the top),
    • 26 |
    • intermediate states (requesting, quoted, Executing)
    • 27 |
    • terminal states (Error, Done, Canceled)
    • 28 |
  • 29 |
  • and transitions between states (arrows)
  • 30 |
31 | 32 |

I find those diagrams very helpfull to think about the system, while building them I will generally go through all the states I already discovered and ask myself the following questions:

33 | 34 |
    35 |
  • could anything else happen in this state?
  • 36 |
  • Any unhappy path? (ie. timeout, error, etc)
  • 37 |
  • Do we have a representation of this particular state for the corresponding UI? (if you are building a UI).
  • 38 |
39 | 40 |

Those diagrams are also very usefull to discuss with non developers: business people, UX, etc.

41 | 42 |

From diagram to code

43 | 44 |

Statemachines can be implemented in many differents ways, either from scratch or using some library. 45 | For any decent size statemachine I tend to use Stateless but the recommendations that follow would stand for any library or hand written statemachine.

46 | 47 |

I like to define state machines in a single place: I find that spreading the definition accross multiple files/classes makes it harder to understand.

48 | 49 |

Stateless offers a nice fluent syntax to define states and possible transitions.

50 | 51 |

Defining states

52 | 53 |

The first thing we need to do is to define the set of states, we can use an enum for that:

54 | 55 |

csharp 56 | public enum RfqState 57 | { 58 | Input, 59 | Requesting, 60 | Cancelling, 61 | Cancelled, 62 | Quoted, 63 | Executing, 64 | Error, 65 | Done 66 | } 67 | 68 | gist

69 | 70 |

Events

71 | 72 |

Then we define the events which will trigger transitions between states. In our case those are events coming from the client or from the server.

73 | 74 |

Again we can use an enum to define those events.

75 | 76 |

```csharp 77 | public enum RfqEvent 78 | { 79 | UserRequests, 80 | UserCancels, 81 | UserExecutes,

82 | 83 |
ServerNewQuote,
 84 | ServerQuoteError,
 85 | ServerQuoteStreamComplete,
 86 | ServerSendsExecutionReport,
 87 | ServerExecutionError,
 88 | ServerCancelled,
 89 | ServerCancellationError,
 90 | 
 91 | InternalError,
 92 | 
93 | 94 |

} 95 | ``` 96 | gist

97 | 98 |

I like to prefix those events with their origin, just to makes things explicit (here we have 'Server', 'User', 'Internal')

99 | 100 |

As you can see events coming from the server always expose a happy path (for instance ServerNewQuote when the server sends a new quote) and at least one corresponding error event (ServerQuoteError).

101 | 102 |

Components

103 | 104 |

You will also often have internal events, for instance a timer expiring can raise an internal event to trigger a state transition.

105 | 106 |

Events may or not carry some data: for instance UserRequests event needs to contain the description of the product being priced. 107 | For those events requiring parameters it is useful to define strongly typed events.

108 | 109 |

This is how we declare them with Stateless, for instance for the ServerSendsQuote event:

110 | 111 |

csharp 112 | _rfqEventServerSendsQuote = _stateMachine.SetTriggerParameters<IQuote>(RfqEvent.ServerNewQuote); 113 | 114 | gist

115 | 116 |

Defining transitions

117 | 118 |

Now we can define transitions. For each state we define which events are allowed and when they are triggered to which state we will transition. 119 | This is very straight forward with stateless:

120 | 121 |

```csharp 122 | _stateMachine.Configure(RfqState.Input) 123 | .Permit(RfqEvent.UserRequests, RfqState.Requesting);

124 | 125 |

_stateMachine.Configure(RfqState.Requesting) 126 | .Permit(RfqEvent.ServerNewQuote, RfqState.Quoted) 127 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 128 | .Permit(RfqEvent.InternalError, RfqState.Error);

129 | 130 |

_stateMachine.Configure(RfqState.Quoted) 131 | .PermitReentry(RfqEvent.ServerNewQuote) 132 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 133 | .Permit(RfqEvent.UserExecutes, RfqState.Executing);

134 | 135 |

_stateMachine.Configure(RfqState.Executing) 136 | .Permit(RfqEvent.ServerSendsExecutionReport, RfqState.Done);

137 | 138 |

_stateMachine.Configure(RfqState.Cancelling) 139 | .Permit(RfqEvent.ServerCancelled, RfqState.Cancelled); 140 | ``` 141 | gist

142 | 143 |

Triggering events

144 | 145 |

When the user performs an action or the server sends back a message we want to fire an event at the state machine. 146 | This is straight forward with stateless

147 | 148 |

```csharp 149 | // for an event without parameters 150 | _stateMachine.Fire(RfqEvent.ServerQuoteStreamComplete)

151 | 152 |

// for a strongly typed event 153 | stateMachine.Fire(rfqEventServerSendsExecutionReport, executionReport) 154 | ``` 155 | gist

156 | 157 |

Defining actions

158 | 159 |

When we send an event to the state machine, two things can happen, the current state has a valid transition for this event or not.

160 | 161 |

If the current state can accept an event we generally want to execute our code at some point around the transition:

162 | 163 |
    164 |
  • when you enter a state (or re-enter a state since it's also possible to have transitions looping back on the same state)
  • 165 |
  • when you exit a state
  • 166 |
  • upon transition, if you have different behavior to implement for different transitions leading to a same state
  • 167 |
168 | 169 |

I tend to apply actions upon entry into a state and use the other variants only in specific scenarios.

170 | 171 |

Important: when implementing a statemachine, you want to put all your logic inside those actions (on state entry, on state exit, on transition) because the state machine has already checked that the incoming event was valid for the current state.

172 | 173 |

Here is an example with Stateless syntax. When the user requests a quote we want to log the transition and also to perform some logic on entry in the requesting state:

174 | 175 |

```csharp 176 | stateMachine.Configure(RfqState.Requesting) 177 | .OnEntry(LogTransition) 178 | .OnEntryFrom(rfqEventUserRequests, OnEntryRequesting) 179 | .Permit(RfqEvent.ServerNewQuote, RfqState.Quoted) 180 | .Permit(RfqEvent.UserCancels, RfqState.Cancelling) 181 | .Permit(RfqEvent.InternalError, RfqState.Error);

182 | 183 |

private void OnEntryRequesting(IQuoteRequest quoteRequest) 184 | { 185 | // here goes the code to send a quote request to the server 186 | } 187 | ``` 188 | gist

189 | 190 |

Tip: you can think of the OnExit action as a Dispose() method for the corresponding state. It is very useful if for instance you had a timer runing during that state and you need to cancel it or you have whatever active Rx query that you want to unsubscribe.

191 | 192 |

Handling errors

193 | 194 |

When an event is fired at the state machine and the state machine has no transition defined for this event in the current state we can implement 2 behaviors: ignoring the event or raising an exception.

195 | 196 |

By default Stateless will raise an exception but you can handle yourself invalid transitions:

197 | 198 |

```csharp 199 | _stateMachine.OnUnhandledTrigger(OnUnhandledTrigger);

200 | 201 |

private void OnUnhandledTrigger(RfqState state, RfqEvent trigger) 202 | { 203 | var message = string.Format("State machine received an invalid trigger '{0}' in state '{1}'", trigger, state); 204 | Console.WriteLine(message);

205 | 206 |
_rfqUpdateSubject.OnError(new ApplicationException(message));
207 | 
208 | 209 |

} 210 | ``` 211 | gist

212 | 213 |

You can also ignore individual events on a state with the Stateless .Ignore() method.

214 | 215 |

Encapsulation

216 | 217 |

We have now defined everything we need for the state machine: 218 | - states, 219 | - events and strongly typed events 220 | - possible transitions 221 | - actions on entry and on exit 222 | - error handling 223 | - how to fire events at the state machine

224 | 225 |

The next step is to encapsulate everything in a single class so we don't leak the specifics of Stateless and the state machine to the rest of our code.

226 | 227 |

For our example I've created a class Rfq that you can find here.

228 | 229 |

This class implements the following interface:

230 | 231 |

```csharp 232 | public interface IRfq : IDisposable 233 | { 234 | void RequestQuote(IQuoteRequest quoteRequest); 235 | void Cancel(long rfqId); 236 | void Execute(IExecutionRequest quote);

237 | 238 |
IObservable<RfqUpdate> Updates { get; } 
239 | 
240 | 241 |

} 242 | ``` 243 | gist

244 | 245 |

This is very much CQRS style: a view model can call the RequestQuote, Cancel and Execute methods which act as Commands and internally fire events. Don't get confused by 'Command' and 'Event', they are the same, it's just that in the context of CQRS we talk about commands and for state machine I've use the term event from the beginning (we could use message as well if we want).

246 | 247 |

The view model also subscribes to the Updates stream which will notify when the state machine transitions and provide the relevant data (a quote, an execution report, etc).

248 | 249 |

You can find some sample usage of this API in the test project.

250 | 251 |

Encapsulation

252 | 253 |

Concurrency

254 | 255 |

I would strongly suggest to get your state machine running on a single thread. In my example the view model MUST call from the UI thread (Dispatcher) and I explicitly marshal server side initiated messages to the UI thread using ObserveOn in my Rx queries.

256 | 257 |

If you are not building a UI you should consider running your statemachine in an actor or an event loop: anything that will guarantee that calls made on the state machine are sequenced and do not have to be synchronized.

258 | 259 |

Why? Simply because otherwise you will have to synchronise all accesses to the state machine (and other states in your encasulating class) with locks. If for instance you take a lock while firing an event, all the actions will run under that lock. Those actions will likely call on code external to this class and you now have risks of deadlock..

260 | 261 |

Race conditions

262 | 263 |

Never forget that in an event driven system things can happen in an order you do not expect, and your state machine should be ready for that.

264 | 265 |

Here is an example, which use a slightly different protocol for the RFQ:

266 | 267 |
    268 |
  • the user receives a valid quote Q1 from the server
  • 269 |
  • the server sends an invalid quote message (to invalidate the quote because the market has moved or for whatever reason)
  • 270 |
  • the user HIT the quote Q1 (executes) while the invalidation message is still in flight (ie. still travelling somewhere between the server and the client)
  • 271 |
  • the state machine transitions to the state 'Executing'
  • 272 |
  • the client receives the invalidate quote message/event but the state machine is in a state where you might not have expected to receive such event...
  • 273 |
274 | 275 |

Because there is a propagation delay between a client and a server, you will see behaviors in your systems that you did not thought about initially and that you have probably not covered in your unit tests.

276 | 277 |

What to do about it?

278 | 279 |
    280 |
  1. For each state go through the list of all possible events and ask yourself: could this one possibly happen in this state? If it does, how should it be handled?
  2. 281 |
  3. Log all transitions of the state machine and all events fired. This is priceless while investigating for such issues.
  4. 282 |
  5. Unit testing is not enough, you will need to test in a deployed environment.
  6. 283 |
284 | 285 |

Visualisation

286 | 287 |

Matt wrote some code which reflectively retrieves the definition of the State machine and is able to produce a graph definition in DOT code (a language to represent graphs).

288 | 289 |

To generate a diagram from the output of the graph generation code, you can either download Graphviz and run it locally, or simply use an online GraphViz webapp.

290 | 291 |

This is the output I got using the webapp:

292 | 293 |

Generated diagram

294 | 295 |

Wrap up

296 | 297 |

It takes a bit of time to get your head around state machines but once you get it those little things yield very nice clean code and it's also very simple to introduce new state and transitions if you follow the few guidelines we discussed here.

298 | 299 |

There are a few other things I'd like to talk about with state machines (for instance visualising them while the system is running, code generation, etc) but we will cover that in a future blog post.

300 | 301 |

I would also suggest to have a look to the work of Pieter Hintjens (ZeroMQ) on state machines and code generation, he has done some very cool stuff in this area

302 | --------------------------------------------------------------------------------