Sha256: 734bcfb7be74737667ac258be1c1d40b5f4f3788f0e0d9bd64ba1c0acd64b8c8

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require 'm2r'

module M2R
  # Connection for exchanging data with mongrel2
  class Connection

    # @param [ZMQ::Socket] request_socket socket for receiving requests
    #   from Mongrel2
    # @param [ZMQ::Socket] response_socket socket for sending responses
    #   to Mongrel2
    # @param [#parse] request_parser Object responsible for parsing Mongrel2
    #   requests
    # @api public
    def initialize(request_socket, response_socket, request_parser = Request)
      @request_socket  = request_socket
      @response_socket = response_socket
      @request_parser  = request_parser
    end

    # For compatibility with {M2R::ConnectionFactory}
    #
    # @return [Connection] self
    # @api public
    def connection
      self
    end

    # Returns parsed Mongrel2 request
    #
    # @note This is blocking call
    # @return [Request] Request parsed by {#request_parser}
    # @api public
    def receive
      @request_socket.recv_string(msg = "")
      @request_parser.parse(msg)
    end

    # Sends response to Mongrel2 for given request
    #
    # @param [Response, #to_s] response_or_string Response
    #   for the request. Anything convertable to [String]
    # @api public
    def reply(request, response_or_string)
      deliver(request.sender, request.conn_id, response_or_string.to_s)
    end

    # Delivers data to multiple mongrel2 connections.
    # Useful for streaming.
    #
    # @param [String] uuid Mongrel2 instance uuid
    # @param [Array<String>, String] connection_ids Mongrel2 connections ids
    # @param [String] data Data that should be delivered to the connections
    #
    # @api public
    def deliver(uuid, connection_ids, data)
      msg = "#{uuid} #{TNetstring.dump([*connection_ids].join(' '))} #{data}"
      @response_socket.send_string(msg)
    end

    private

    attr_reader :request_socket
    attr_reader :response_socket
    attr_reader :request_parser
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
m2r-1.0.0 lib/m2r/connection.rb