mongodb/mongo-ruby-driver — pull request #205 by TylerBrock (2013-06-02 17:27:58+00:00)
Title: RUBY-595 abstract Message base class

This is the initial commit for implementation of the modeled MongoDB wire protocol.

### The Idea
Provides an abstract base class named `Message` that all messages will subclass.

I chose to use a class instead of a module because for modeling `Message` because I believe the relationship between `Message` and messages is best defined as a "is-a" relationship instead of a "behaves-like" relationship and has the benefit of clearly delineating methods which are public (`#serialize` and `#deserialize`) from those which are protected and called only by the subclasses of Message (`#field`).

### The DSL
The basic functionality included in the Message class allows for messages to be defined through the use of field declarations. Fields are denoted, in order, by name and type (implying a particular serialization strategy) through a simple DSL:

```ruby
field :length, Int32
field :namespace, CString
field :document, Document
```

### Serialization and Deserialization
The serialization strategies contained in the Serializers module each have their own submodule in order to quickly and directly invoke the correct strategy for a field.

### Request IDs
New request ids are generated atomically, admittedly not in the most performant way, each time the public serialize method is invoked in order to easily send multiple requests of the same type (subsequent GetMore messages for example).

Other strategies, such as simply setting the request id to a fixed number or randomly generating a 32bit integer (such as the python driver), in my opinion, are unacceptable given the possibility of future asynchronous capability. We can improve upon the performance of the implementation using a hash of thread id and a counter masked into the 32 bit field however at this point I wanted to do the clearest thing and leave optimizations to a later revision.

### Performance Note
Moped does not generate request ids and requires that the user of the API provide one upon message instantiation. Barring this discrepancy and it's penalty on performance, this implementation exceeds the performance of Moped's.