class Fastbeans::Request

Constants

OPTION_KEYS
RESPONSE_READ_TIMEOUT

Attributes

connection[R]

Public Class Methods

new(connection, opts = {}) click to toggle source
# File lib/fastbeans/request.rb, line 12
def initialize(connection, opts = {})
  @connection = connection
  @options = {:timeout => RESPONSE_READ_TIMEOUT}.update(opts)
end

Public Instance Methods

build_payload(call_data) click to toggle source
# File lib/fastbeans/request.rb, line 21
def build_payload(call_data)
  signature = sign(call_data)
  signed_data = [signature, call_data]
  payload = MessagePack.pack(signed_data)
  if payload.respond_to?(:force_encoding)
    payload.force_encoding('BINARY')
  end
  [signature, payload]
end
perform(call_data) click to toggle source
# File lib/fastbeans/request.rb, line 46
def perform(call_data)
  connection.with_socket do |sock|
    signature, payload = build_payload(call_data)
    write_payload(sock, payload)
    resp = read_response(sock, call_data)
    if resp.error? or resp.signed_with?(signature)
      resp.payload
    else
      raise ResponseSignatureMismatch, "Received #{resp.signature} signature instead of expected #{signature} for #{call_data} call"
    end
  end
end
read_response(sock, call_data) click to toggle source
# File lib/fastbeans/request.rb, line 36
def read_response(sock, call_data)
  raw_resp = Timeout.timeout(@options[:timeout], Fastbeans::ResponseReadTimeout) do
    MessagePack.load(sock)
  end
  Fastbeans::Response.new(call_data, raw_resp)
rescue Fastbeans::ResponseReadTimeout
  @connection.disconnect!
  raise Fastbeans::ResponseReadTimeout, "Couldn't read response in #{@options[:timeout]} seconds"
end
sign(call_data) click to toggle source
# File lib/fastbeans/request.rb, line 17
def sign(call_data)
  Digest::MD5.hexdigest(call_data.inspect)
end
write_payload(sock, payload) click to toggle source
# File lib/fastbeans/request.rb, line 31
def write_payload(sock, payload)
  sock.write([payload.bytesize].pack('N'))
  sock.write(payload)
end