Tuesday, June 28, 2011

ETags and optimistic concurrency control with WCF Web Apis

In my previous post I wrote about how to take advantage of ETags to implement HTTP cache validation with WcfWebApis, but this is not the only use of ETags, you can also use them to implement optimistic concurrency control over HTTP. The following workflow illustrates this feature:

  1. The client wants to get a resource and for that it sends a GET request and the server answers with the resource representation and its ETag.
  2. The client decides to update the resource and for that it sends a PUT request with the modified resource representation along with the ETag from the previous step.
  3. The server checks the incoming ETag against the current resource representation ETag from its repository (i.e: Cache, DB).
    • If they match, the server carries on with the resource update and returns a 200 HTTP status if it succeeds.
    • If they don’t match, it’s because someone else has updated the resource in the meantime. Therefore the server invalidates the request and returns a 402 Precondition Failed status. (Concurrency error)

Now replace “GET” by “SELECT” and “PUT” by “UPDATE… WHERE” and this is exactly the same optimistic concurrency mechanism that you can usually find implemented in relational databases.

Enough of theory, we can implement step 3 from the workflow with a DelegatingChannel. The channel takes advantage of the ETag cache that I used in my previous post.

public class EntityTagConcurrencyChannel : DelegatingChannel
{
    private readonly ETagCache _eTagCache = ETagCacheProvider.Instance;
 
    public EntityTagConcurrencyChannel(HttpMessageChannel innerChannel)
        : base(innerChannel)
    {
 
    }
 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
                                                  CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Put && 
            request.Headers.IfNoneMatch.Any())
        {
            var etag = request.Headers.IfNoneMatch.First().ToString();
            if (etag != "*")
            {
                var cached = _eTagCache.Get(request.RequestUri.ToString());
                return etag != cached
                  ? Task.Factory.StartNew(() => CreatePreconditionFailedResponse(),
                                                    cancellationToken)
                  : base.SendAsync(request, cancellationToken);
            }
        }
        return base.SendAsync(request, cancellationToken);
    }
 
    private static HttpResponseMessage CreatePreconditionFailedResponse()
    {
        return new HttpResponseMessage(HttpStatusCode.PreconditionFailed, 
                                        "If-None-Match");
    }
}
As per the HTTP specification, the special wildcard “*” value makes the server not to run the validation.

6 comments:

  1. I'm happy about everything you bring it very interesting and helpful, thanks
    Signature:
    i like play games friv online and play games2girls 2 online free and play game friv games and games 2 girls ! have fun!

    ReplyDelete
  2. This is also a very good post which I really enjoyed reading. It is not everyday that I have the possibility to see something
    Jugar juegos de frozen en línea gratis, los nuevos de princesa de Disney juegos frozen - la princesa encantadora y linda. Divertirse frozen

    ReplyDelete
  3. What a great online source of information about this topic. you have done great work. keep continue to sharing such kinds of post. keep it up.
    Signature:
    facebook entrar iniciar sesion gratis - Sitio Oficial iniciado sesión en Facebook lengua española. facebook entrar rápido, facebook iniciar sesion en tu cuenta de entrar facebook

    ReplyDelete
  4. I was working and suddenly I visits your site frequently and recommended it to me to read also. The writing style is superior and the content is relevant. Thanks for the insight you provide the readers!
    Signature:
    Versión en facebook en español descargar a los países hablan Español: facebook entrar direto agora , facebook en español descargar , facebook entrar direto agora

    ReplyDelete
  5. Great info. I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks for sharing.
    Signature:
    download facebook movel, baixar Facebook movel, baixar facebook. Facebook chat, baixar whatsapp, fazer o download whatsapp baixar para Android, iPhone. Últimas Facebook

    ReplyDelete
  6. This is also a very good post which I really enjoyed reading. It is not everyday that I have the possibility to see something
    Signature:
    The place to play all unblockedgames online. Here you can find every blocked games such as: unblocked games , unblocked games happy , unblocked games 77 ,

    ReplyDelete