This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.
Channels are possibly the most fundamental concept in WCF that (almost) nobody knows about. This is quite a heavy subject, so I’ll break it down in two parts: this post will deal with the concepts for channels and the client part, and the next one will dive deeper into the server part of the channels.
Channels (also known as “protocol channels”) make up the stack over which WCF messages are sent and received. They are called “protocol channels” because they’re usually used to implement some sort of, well, protocol between the communicating parties. Security (WS-Security), reliable messaging (WS-RM), transactions (WS-Transaction), composite duplex (where two HTTP connections are used to implement a duplex pattern over HTTP, which is a request/reply protocol), those are all implemented as channels in WCF. Other examples, such as the Polling Duplex protocol from Silverlight, or the chunking protocol implemented by the Chunking Channel sample are also implemented internally as channels. Channels can do essentially anything with the message: change it, add / remove headers, fiddle with its properties, invoke user code (which I used on the post about extensibility points for Windows Phone / Silverlight 3), even change the message completely. The channel then passes the message to the “inner” channel until it reaches the final destination - for outgoing messages (the request on the client side, the reply on the server), it’s the transport which will send the message over the wire; for incoming messages (request on server, reply on client), it’s the formatter which will unwrap the parameters out of the message to either call the service operation or send the result back to the client code. The diagram below has been drawn in many similar ways and shapes, but it illustrates quite well the path that a request takes from the client to the server (for the response, just invert the direction of the vertical arrows).
But this diagram doesn’t even tell everything that a channel can do: it doesn’t have to receive one message, play with it and pass it along. It can take one message, then send several of them – for example, a very time-sensitive client can send multiple requests to different services, and take the first response thus reducing the odds it will hit a dead server. It can, even before a client sends a request, to do some communication with the server side – the protocol can do some handshaking when the channel is being opened (and also do some teardown handshaking when the channel is being closed). It can even not send the message to the inner channel – and thus bypass the whole stack returning a message directly to the caller. The same can be done for incoming messages as well – a channel can simply inspect / modify the incoming message and pass it along, it can collect many messages and aggregate them into a single message to pass it along (like in the Chunking Channel sample), or it can simply deal with the message directly without passing it along (in the case of handshaking messages, for example). Channels can also be used where the “normal” extensibility points don’t work, for example, to catch errors in the channels themselves, outside of the service model realm.
One aside about encoders: many diagrams for channels in WCF put them in the same category as the other channels. In fact, they should not be considered as such. On outgoing messages, the last protocol channel in the stack doesn’t hand its message to the encoder for processing – it hands it over to the last channel in the stack, the transport channel. It’s the transport which may use an encoder in the binding context to convert the message into bytes to send over the wire (it doesn’t have to, it can do the encoding itself if the implementation so desires). Similarly for incoming messages, the transport may use the encoder to decode the bytes into a Message object, and then it passes it along to the next protocol channel in the stack. I’ll cover encoders in more details in an upcoming post about them.
There are many different shapes (or kinds) of channels in the WCF pipeline. Depending on the message exchanging pattern which is being used, a certain kind of channel needs to be used, so the type of custom channel you need to write will be determined by the pattern as well. The list below shows briefly the types of WCF channels:
- IOutputChannel: Defines a channel which can only send messages. Useful in one-way communication.
- IInputChannel: The receiving counterpart of the IOutputChannel, defines a channel which can only receive messages
- IRequestChannel: Defines a channel which can send a message, and return a response to it. Useful in request/reply protocols such as HTTP
- IReplyChannel: The receiving counterpart of the IRequestChannel, defines a channel which can receive a request and reply with another message
- IDuplexChannel: Defines a channel which can both send and receive messages independently. A duplex channel is equivalent to a pair of IInputChannel and IOutputChannel.
In addition to those basic shapes, there are also their session-full equivalent which extend their contract by also implementing ISessionChannel to support session-full communication: IOutputSessionChannel, IInputSessionChannel, IRequestSessionChannel, IReplySessionChannel and IDuplexSessionChannel.
Notice that the channels in the stack don’t need to be all of the same shape: it’s possible that protocol channels are used to modify the shape of the communication as well. For example, the composite duplex channel (used in the WSDualHttpBinding) converts an output (in the sender) and input (in the receiver) channels into a duplex channel (a duplex session channel, actually), by essentially creating a “server” at the client side. The reliable messaging channel, used in WSHttpBinding, adds a session to the HTTP transport (essentially transforming an IRequestChannel into an IRequestSessionChannel at the client, and an IReplyChannel into an IReplySessionChannel at the server). And so on.
So, channels are very powerful, very flexible, and can do a lot of nice features. Why aren’t they used more widely then? First of all, they’re difficult to implement. Even for simple channels which just pass along a message to the inner channel and don’t do anything like shape changing, there is a lot of code which needs to be written (in the example later in this post you’ll see what I’m talking about). Also, channels deal with Message objects. Unless one is very versed in SOAP-speak, chances are they just want to define a service and let WCF (or whichever stack they’re using) take care of the protocols underneath. And start throwing asynchronous code paths which can be used, the implementation of even the simplest of the channels can become complex quickly. So most people (with very good reason), myself included, avoid going down to the channel level unless it’s absolutely necessary.
Public implementations in WCF
None. All channels in WCF (and in most examples I’ve seen) are implemented either as internal or nested (private) classes of the binding elements which add them. Since the channels can only be created following a certain pattern (the binding element creates the channel factory / listener, then the factory / listener creates the appropriate channel), it doesn’t make sense for those classes to be public (maybe with the exception for unit testing purposes)
The interfaces for the channel shapes have so many methods that I’ll skip this section in this post – follow the links on the channel shapes section for them.
How to add custom channels (client side)
Channels stacks are created using the factory pattern from the binding. So to create a custom channel, one needs to write a binding element, and create a binding containing this element. The binding element class would override CanBuildChannelFactory<TChannel> (to determine whether the channel shape is supported) and BuildChannelFactory<TChannel> to actually return a channel factory which is capable of building the requested channel type. The channel factory implementation needs to override the CreateChannel methods (or OnCreateChannel, if the class inherits from ChannelFactoryBase<TChannel>), besides a lot of boilerplate methods (Open, BeginOpen, EndOpen, Close, etc.) to finally return the channel which will be used in the pipeline. To illustrate the verboseness of all of this, this is I think the simplest code to write a client channel that I can think of (it just passes the message along, and supports only IRequestChannel).
As I mentioned before, that’s a lot of code for a channel which does absolutely nothing…
Real world scenario: a Chaos Monkey channel
One very interesting blog post I’ve seen lately was the Netflix team describing their experience using Amazon Web Services for their product, and Jeff Atwood’s post about it in the aftermath of the big outage suffered by AWS. One of the techniques used by Netflix to ensure a good response is what they called the “Chaos Monkey”, whose job is to randomly kill instances and services in their architecture, to ensure that the other parts which depended on them were resilient to errors and normal downtime of the network systems. With that chaos resiliency, Netflix didn’t suffer nearly as much as other companies when AWS stopped working for extended periods of time.
If we are building an application which talks to services, and we want to emulate that technique, we can also periodically disconnect / shut down the services and add guards in our application to deal with those situations. But in many cases we don’t really own the services we’re talking to, so we can’t do exactly that. Enter the “chaos monkey channel”, one implementation of a WCF channel which occasionally throws wrenches in the code by returning a custom messages (normally a fault for SOAP-based services). In this implementation I’m using a “chaos controller” which lets the user define via an interface how much “chaos” they want to introduce into the system.
And before I go further, the usual disclaimer: this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few contracts and it worked, but I cannot guarantee that it will work for all scenarios - it does not work for TCP (duplex) or one way (IInput / IOutput) channels. Please let me know if you find a bug or something missing. A more complete implementation would also include support for more channel types, and possibly provide some helper methods for the user to create known faults (i.e., from the fault contract of the operation) instead of leaving it completely up to the user.
To start off, the interface which allows the user to add “chaos” to the system. I tried to keep it simple, but it could be made more user-friendly so that the user wouldn’t need to deal with Message objects directly, but I opted for simplicity on the channel itself.
Next I had to decide which channel shape to use. Since HTTP is the most common protocol used in communication, I started with an IRequestChannel implementation, which worked fine for a custom binding based on the BasicHttpBinding. Here’s the binding element which can be added.
On to the channel factory. Implementing it for this scenario was fairly simple, just with a bunch of boilerplate methods which delegated the call to the factory of the next element in the binding element stack.
Finally the channel itself. To keep the channel simple, I removed the code which dealt with messages and moved it into a separate (private) helper class, so the implementation of the request channel itself would be kept simple.
The synchronous path of the helper class is fairly straightforward: if the controller says that we should return a fault, we just return the message returned by the chaos controller, and the rest of the stack is bypassed (the request won’t be sent to the server). On the asynchronous case, we need to return an IAsyncResult to the caller, and depending on whether the chaos should happen or not, this asynchronous result will come from different sources. Here I used the same pattern as I described in the post about operation invokers, in which the response is wrapped in a custom IAsyncResult implementation (I’ll omit the class CorrelatingAsyncResult in this post, it can be seen in the code for this post link at the bottom).
And that’s it – we can now test it. For that I’ll use a very simple server (a simple Add operation) and controller (which randomly creates problems for 20% of the messages).
And running the code below, we see that many of the requests to the service throw an exception, just as we wanted. We have chaos!
Since it worked for a simple HTTP binding, I tried changing it to WSHttpBinding instead of a BasicHttpBinding. And now nothing worked – the channel in the client could not be created! The problem was that while the HTTP transport can only build IRequestChannel instances, WSHttpBinding adds a ReliableMessagingBindingElement to the stack, and it changes the shape to an IRequestSessionChannel. And we have to go back to the binding element to add support for it again… which means writing a new factory (IChannelFactory<IRequestSessionChannel>) and a new ISessionChannel implementation. And here goes a lot more code… This is the new implementations of [Can]BuildChannelFactory<TChannel> on the binding element.
The implementation of the factory and the channel are really similar to the IRequestChannel. But since we’re passing an inner factory / channel of a certain type, we can’t really reuse much of the code and we end up with a lot of copy/paste code.
Finally, channels are powerful. And I’ve mentioned it before and will do it again – only use it when no other extensibility points can be used for your needs. But if you really need them, hopefully this post will help you a little in understanding them.
More channels – this time at the server side (listeners).