Class: Mongo::Protocol::Message Abstract

Inherits:
Object
  • Object
show all
Includes:
Id, Serializers
Defined in:
lib/mongo/protocol/message.rb

Overview

This class is abstract.

A base class providing functionality required by all messages in the MongoDB wire protocol. It provides a minimal DSL for defining typed fields to enable serialization and deserialization over the wire.

Examples:

class WireProtocolMessage < Message

  private

  def op_code
    1234
  end

  FLAGS = [:first_bit, :bit_two]

  # payload
  field :flags, BitVector.new(FLAGS)
  field :namespace, CString
  field :document, Document
  field :documents, Document, true
end

Direct Known Subclasses

Compressed, GetMore, KillCursors, Msg, Query, Reply

Constant Summary collapse

BATCH_SIZE =

The batch size constant.

Since:

  • 2.2.0

'batchSize'
COLLECTION =

The collection constant.

Since:

  • 2.2.0

'collection'
LIMIT =

The limit constant.

Since:

  • 2.2.0

'limit'
ORDERED =

The ordered constant.

Since:

  • 2.2.0

'ordered'
Q =

The q constant.

Since:

  • 2.2.0

'q'
MAX_MESSAGE_SIZE =

Default max message size of 48MB.

Since:

  • 2.2.1

50_331_648

Constants included from Serializers

Serializers::HEADER_PACK, Serializers::INT32_PACK, Serializers::INT64_PACK, Serializers::NULL, Serializers::ZERO

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Id

included

Constructor Details

#initialize(*_args) ⇒ Message

:nodoc:



77
78
79
# File 'lib/mongo/protocol/message.rb', line 77

def initialize(*_args) # :nodoc:
  set_request_id
end

Instance Attribute Details

#request_idFixnum (readonly)

Returns the request id for the message

Returns:

  • (Fixnum)

    The request id for this message



84
85
86
# File 'lib/mongo/protocol/message.rb', line 84

def request_id
  @request_id
end

Class Method Details

.deserialize(io, max_message_size = MAX_MESSAGE_SIZE, expected_response_to = nil, options = {}) ⇒ Message

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deserializes messages from an IO stream.

This method returns decompressed messages (i.e. if the message on the wire was OP_COMPRESSED, this method would typically return the OP_MSG message that is the result of decompression).

Parameters:

  • max_message_size (Integer) (defaults to: MAX_MESSAGE_SIZE)

    The max message size.

  • io (IO)

    Stream containing a message

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :deserialize_as_bson (Boolean)

    Whether to deserialize this message using BSON types instead of native Ruby types wherever possible.

  • :socket_timeout (Numeric)

    The timeout to use for each read operation.

Returns:

  • (Message)

    Instance of a Message class

Raises:



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/mongo/protocol/message.rb', line 235

def self.deserialize(io,
                     max_message_size = MAX_MESSAGE_SIZE,
                     expected_response_to = nil,
                     options = {})
  # io is usually a Mongo::Socket instance, which supports the
  # timeout option. For compatibility with whoever might call this
  # method with some other IO-like object, pass options only when they
  # are not empty.
  read_options = options.slice(:timeout, :socket_timeout)

  chunk = if read_options.empty?
            io.read(16)
          else
            io.read(16, **read_options)
          end
  buf = BSON::ByteBuffer.new(chunk)
  length, _request_id, response_to, _op_code = deserialize_header(buf)

  # Protection from potential DOS man-in-the-middle attacks. See
  # DRIVERS-276.
  raise Error::MaxMessageSize.new(max_message_size) if length > (max_message_size || MAX_MESSAGE_SIZE)

  # Protection against returning the response to a previous request. See
  # RUBY-1117
  if expected_response_to && response_to != expected_response_to
    raise Error::UnexpectedResponse.new(expected_response_to, response_to)
  end

  chunk = if read_options.empty?
            io.read(length - 16)
          else
            io.read(length - 16, **read_options)
          end
  buf = BSON::ByteBuffer.new(chunk)

  message = Registry.get(_op_code).allocate
  message.send(:fields).each do |field|
    if field[:multi]
      deserialize_array(message, buf, field, options)
    else
      deserialize_field(message, buf, field, options)
    end
  end
  message.fix_after_deserialization if message.is_a?(Msg)
  message.maybe_inflate
end

.deserialize_array(message, io, field, options = {}) ⇒ Message

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deserializes an array of fields in a message

The number of items in the array must be described by a previously deserialized field specified in the class by the field dsl under the key :multi

Parameters:

  • message (Message)

    Message to contain the deserialized array.

  • io (IO)

    Stream containing the array to deserialize.

  • field (Hash)

    Hash representing a field.

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :deserialize_as_bson (Boolean)

    Whether to deserialize each of the elements in this array using BSON types wherever possible.

Returns:

  • (Message)

    Message with deserialized array.



382
383
384
385
386
387
# File 'lib/mongo/protocol/message.rb', line 382

def self.deserialize_array(message, io, field, options = {})
  elements = []
  count = message.instance_variable_get(field[:multi])
  count.times { elements << field[:type].deserialize(io, options) }
  message.instance_variable_set(field[:name], elements)
end

.deserialize_field(message, io, field, options = {}) ⇒ Message

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deserializes a single field in a message

Parameters:

  • message (Message)

    Message to contain the deserialized field.

  • io (IO)

    Stream containing the field to deserialize.

  • field (Hash)

    Hash representing a field.

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :deserialize_as_bson (Boolean)

    Whether to deserialize this field using BSON types wherever possible.

Returns:

  • (Message)

    Message with deserialized field.



401
402
403
404
405
406
# File 'lib/mongo/protocol/message.rb', line 401

def self.deserialize_field(message, io, field, options = {})
  message.instance_variable_set(
    field[:name],
    field[:type].deserialize(io, options)
  )
end

.deserialize_header(io) ⇒ Array<Fixnum>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deserializes the header of the message

Parameters:

  • io (IO)

    Stream containing the header.

Returns:

  • (Array<Fixnum>)

    Deserialized header.



336
337
338
# File 'lib/mongo/protocol/message.rb', line 336

def self.deserialize_header(io)
  Header.deserialize(io)
end

.field(name, type, multi = false) ⇒ NilClass

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

A method for declaring a message field

Parameters:

  • name (String)

    Name of the field

  • type (Module)

    Type specific serialization strategies

  • multi (true, false, Symbol) (defaults to: false)

    Specify as true to serialize the field’s value as an array of type :type or as a symbol describing the field having the number of items in the array (used upon deserialization)

    Note: In fields where multi is a symbol representing the field
    containing number items in the repetition, the field containing
    that information *must* be deserialized prior to deserializing
    fields that use the number.
    

Returns:

  • (NilClass)


356
357
358
359
360
361
362
363
364
# File 'lib/mongo/protocol/message.rb', line 356

def self.field(name, type, multi = false)
  fields << {
    name: :"@#{name}",
    type: type,
    multi: multi
  }

  attr_reader name
end

.fieldsInteger

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

A class method for getting the fields for a message class

Returns:

  • (Integer)

    the fields for the message class



327
328
329
# File 'lib/mongo/protocol/message.rb', line 327

def self.fields
  @fields ||= []
end

Instance Method Details

#==(other) ⇒ true, false Also known as: eql?

Tests for equality between two wire protocol messages by comparing class and field values.

Parameters:

Returns:

  • (true, false)

    The equality of the messages.



287
288
289
290
291
292
293
294
295
# File 'lib/mongo/protocol/message.rb', line 287

def ==(other)
  return false if self.class != other.class

  fields.all? do |field|
    name = field[:name]
    instance_variable_get(name) ==
      other.instance_variable_get(name)
  end
end

#hashFixnum

Creates a hash from the values of the fields of a message.

Returns:

  • (Fixnum)

    The hash code for the message.



301
302
303
# File 'lib/mongo/protocol/message.rb', line 301

def hash
  fields.map { |field| instance_variable_get(field[:name]) }.hash
end

#maybe_add_server_api(server_api) ⇒ Object

Protocol message subclasses that support the server api option should override this method to add the server api document to the message.

Parameters:

  • server_api (Hash)

    The server api document to add to the message.

Raises:

  • (NotImplementedError)


175
176
177
# File 'lib/mongo/protocol/message.rb', line 175

def maybe_add_server_api(server_api)
  raise NotImplementedError
end

#maybe_compress(_compressor, _zlib_compression_level = nil) ⇒ self

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Compress the message, if supported by the wire protocol used and if the command being sent permits compression. Otherwise returns self.

Parameters:

  • compressor (String, Symbol)

    The compressor to use.

  • zlib_compression_level (Integer)

    The zlib compression level to use.

Returns:

  • (self)

    Always returns self. Other message types should override this method.

Since:

  • 2.5.0



110
111
112
# File 'lib/mongo/protocol/message.rb', line 110

def maybe_compress(_compressor, _zlib_compression_level = nil)
  self
end

#maybe_decrypt(_context) ⇒ Mongo::Protocol::Msg

Possibly decrypt this message with libmongocrypt.

Parameters:

Returns:

  • (Mongo::Protocol::Msg)

    The decrypted message, or the original message if decryption was not possible or necessary.



150
151
152
153
154
155
156
# File 'lib/mongo/protocol/message.rb', line 150

def maybe_decrypt(_context)
  # TODO: determine if we should be decrypting data coming from pre-4.2
  # servers, potentially using legacy wire protocols. If so we need
  # to implement decryption for those wire protocols as our current
  # encryption/decryption code is OP_MSG-specific.
  self
end

#maybe_encrypt(_connection, _context) ⇒ Mongo::Protocol::Msg

Possibly encrypt this message with libmongocrypt.

Parameters:

Returns:

  • (Mongo::Protocol::Msg)

    The encrypted message, or the original message if encryption was not possible or necessary.



166
167
168
169
# File 'lib/mongo/protocol/message.rb', line 166

def maybe_encrypt(_connection, _context)
  # Do nothing if the Message subclass has not implemented this method
  self
end

#maybe_inflateProtocol::Message

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Inflate a message if it is compressed.

Returns:

  • (Protocol::Message)

    Always returns self. Subclasses should override this method as necessary.

Since:

  • 2.5.0



140
141
142
# File 'lib/mongo/protocol/message.rb', line 140

def maybe_inflate
  self
end

#number_returned0

Default number returned value for protocol messages.

Returns:

  • (0)

    This method must be overridden, otherwise, always returns 0.

Since:

  • 2.5.0



319
320
321
# File 'lib/mongo/protocol/message.rb', line 319

def number_returned
  0
end

#replyable?false

The default for messages is not to require a reply after sending a message to the server.

Examples:

Does the message require a reply?

message.replyable?

Returns:

  • (false)

    The default is to not require a reply.

Since:

  • 2.0.0



95
96
97
# File 'lib/mongo/protocol/message.rb', line 95

def replyable?
  false
end

#serialize(buffer = BSON::ByteBuffer.new, max_bson_size = nil, bson_overhead = nil) ⇒ String Also known as: to_s

Serializes message into bytes that can be sent on the wire

Parameters:

  • buffer (String) (defaults to: BSON::ByteBuffer.new)

    buffer where the message should be inserted

Returns:

  • (String)

    buffer containing the serialized message



200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/mongo/protocol/message.rb', line 200

def serialize(buffer = BSON::ByteBuffer.new, max_bson_size = nil, bson_overhead = nil)
  max_size =
    if max_bson_size && bson_overhead
      max_bson_size + bson_overhead
    elsif max_bson_size
      max_bson_size
    end

  start = buffer.length
  serialize_header(buffer)
  serialize_fields(buffer, max_size)
  buffer.replace_int32(start, buffer.length - start)
end

#set_request_idFixnum

Generates a request id for a message

Returns:

  • (Fixnum)

    a request id used for sending a message to the server. The server will put this id in the response_to field of a reply.



310
311
312
# File 'lib/mongo/protocol/message.rb', line 310

def set_request_id
  @request_id = self.class.next_id
end