Tuesday, February 25, 2014

Quick and Dirty Command Bus with F#

When developing a new application that could benefit from the Domain Drive Design (DDD), Command Query Responsibility Segregation (CQRS), and Event Sourcing (ES) I like to start out with a "quick and dirty" stack, if you will. It should meet the needs of the application in the beginning with extensibility points baked in so that I can scale out in the areas that make sense. One of the hardest parts about this is worrying about how to serialize commands to command handlers in a way that can be scaled.

One of the interesting pieces of F# (which is not F# specific, of course) is the built-in use of agent-based programming. Using the built-in MailboxProcessor we can easily write a miniature command and event bus. Not having to worry about how to build this specific piece of infrastructure (to start) allows us to focus on building the application and then plug in new pieces as we need. For many applications this approach will probably be "good enough" and might solve our needs.

So, let's take a look at what we want from our buses. Let's ignore, for now, the fact that a command should only every be handled by one command handler. Our application is just starting out, it's small, and we can keep the pieces in our head. We aren't loading up assemblies in some dynamic nature so we can visibly look at a module and see what handlers are registered. (If you can't do this, it might be time to move up a level.) Since we're not going to explicitly determine that a command must only be handled by one handler, we can assume that the two buses (Event and Command, that is) can behave the same way. A "message" comes in and it gets handed off, in a serialized fashion, to the "listeners".

This post will cover the command bus.

Command Router Interface

Let's define a little interface for our command router (the bus).

This simple little thing allows us to create different buses as we need. Of course, to start, we'll just need something to allow us to send commands into the domain. Let's now define the look of our command. We probably want to know who sent in the command, the id of the entity we're targeting, and the command itself.

So here we have a discriminated union that describes who sent the command, a record that describes some "header data" that we might need, and then the "command." The "body" portion of the "Command" record is where we'll tuck away the actual command. (We're using obj instead of a generic to make our life a little easier later. Cheating, yeah.)

Create the darn thing

Let's put our IRouter interface to work. We're only going to have one instance of the bus but we might have multiple buses. We can put together a helper function that takes in our "handlers" and returns us an instance of the bus. A handler is just a function that takes a command and returns unit (void).

Now we can wire it up to our application. Since I am partial to Simple.Web and StructureMap, I'm going to show that here, but it should be fairly obvious how to do this in your preferred framework.

I'm punting for now and putting in some fake "createHandlerN" functions into a list and then passing it into the command router function. In my next post I'll cover what those look like and how to make this play nicely with a simple event bus using NEventStore. Until then, I'm always open for feedback on what I have presented and am interested in how you might have solved this sort of problem yourself! Overall, though, nothing difficult about this and it will help us break apart our applications very nicely.

Sunday, February 23, 2014

Simple.Web F# Project IPathUtility Fix

I just pushed an update the F# Simple.Web Visual Studio extension with a minor (well, pretty major) update. When I removed the Simple.Web.AspNet NuGet package, it also removed a utility that is required by Simple.Web (and is the only real code baked into Simple.Web.AspNet). Since Simple.Web is not reliant upon IIS and is written on top of OWIN, it requires an IPathUtility instance to know where to load the files. The interface is very simple and is found in System.Web.Hosting. I basically lifted the code out of the NuGet package and added it to OwinAppSetup.fs. That way, if you don't want to use IIS, you can easily change the code right there to map virtual paths to the hard disk however you want.

Our OwinAppSetup.fs now contains:

I'm sorry if this caused any headache for anybody!

Thursday, February 6, 2014

Please Don't be Afraid of Command Query Responsibility Segregation (CQRS)

I know that I'm not the only person who has said this and I'm probably not going to be the last, but after discussing this very thing with a few people I think it is worth emphasizing. When I talk to other developers about what images the four words "Command Query Responsibility Separation" conjure, it is interesting. Often times I hear elaborate stories about event sourcing, eventual consistency, and a lot of crazy technology stacks.

It is a shame that this idea seems to be so prevalent, causing a lot of developer to discard it as overly complicated. If we look at the words that comprise the acronym, it seems silly that we attribute so much to it. In my mind, we have wrapped up so many ideas into this simple concept that it is almost like freaking out because somebody is attempting to use SOLID development practices. (Watch out for all of those crazy classes and interfaces!) At its core, CQRS is simple. Very simple. The idea is that we recognize that a call from an outside entity to mutate the state of our application and a call to get state information are two totally separate things. And, as such, should be modeled differently.

Real world pain

I worked on a project that interfaced with a COBOL "backend" for the government. One of the things that we had to face on that project was how the COBOL programmers viewed the world. When we needed to query anything or send in a "command" it would use, in their terms, the same screen. Basically, they had an old green screen AS-400 set of screens (over 200) that we just pushed data into and pulled it out of over a WSDL endpoint. It made it absolutely impossible for us to gain any context on the web side of the world because the same "screen" was used to ask for data and to mutate it. We also had to serialize a hundreds of empty fields back to the COBOL application with maybe one or two filled in just to get some data back. Needless to say this was a painful and error-prone process.

Once the web world had kind of taken over my team thought (foolishly) that we would start writing the logic on our side and deprecate the COBOL world. Unfortunately, development continued in the COBOL application. What we were able to do, though, was talk to the COBOL developers and get them to change the way we requested information. We found out that the "screens" we were sending back and forth did not, in fact, have to have identical fields. It was just how they had always done it when interfacing with the green screen.

After some discussion, we actually got a few of the new programs to utilize different fields for input and output. This even went so far as to breaking apart a few of the monolithic monsters that that gave us huge headaches and were pretty much impossible to test. (I'm talking QA testing, too. Unit/Integration tests were impossible.) This really helped speed up the development process and allowed a cleaner definition of what was required for input versus output. This was especially helpful for screens that returned collections. Before the change, we would have to send a request with (hundreds) of empty rows just so the COBOL program would have the correct data.

Oh, and this application is still being developed as of today. This isn't some horror story from the 90s.

CQRS versus the Command Pattern

Another thing to watch out for is mixing up ideas from the Command Pattern and CQRS. The commands in CQRS are not the same thing. Usually, in the command pattern, the command has an execute method on it that does the actual work. That is not how the commands work for CQRS. The commands should be built as Plain Old (Insert your development framework/language here) Objects. For us in the .NET world those are POCOs and, for Java devs, POJOs. (As was kindly pointed out in the comments: just a data structure.) They are just property bags that carry the intent of the user (a human or another system) to the domain.

Eventual Consistency

This is another thing that constantly gets tied to CQRS. Unfortunately, there is absolutely no reason that we have to have eventual consistency with CQRS. It is perfectly fine to inject a command handler into your web endpoint and pass in the command directly. We don't need a command bus to enjoy the magic of CQRS. And along with this, we also get:

Event Systems

And, for that matter, we don't have to have event systems in place to make use of CQRS. These are things that we can add to our system as we need to scale out and get a better feel for our domain. If these things are a requirement for your domain, obviously plan ahead and make extension points where you can plug these things in.

Why the confusion and over complication?

When I was able to make the shift over and try it out, plainly, without the overhead and complications I could see why. It is liberating. Once I broke everything apart and started practicing CQRS I could see how I could really empower my systems and make them even more decoupled by taking the next step. Adding in a command bus and event sourcing is a natural progression. Even so, we can implement a cheaper version of the two without a bunch of crazy overhead. This is made even more possible with (you guessed it!) F#. This will be the topic of my next post, so stay tuned!