Sha256: b2861765433d99bebbdaf796a5f5f9e8351aff565be46614cb05e83f289f5bb2

Contents?: true

Size: 1.79 KB

Versions: 5

Compression:

Stored size: 1.79 KB

Contents

require 'tamashii/agent/common'
require 'tamashii/agent/request_pool/request'
require 'tamashii/agent/request_pool/response'


module Tamashii
  module Agent
    class RequestPool
      include Common::Loggable
      def initialize
        @pool = {}
        @handlers = {}
      end

      def set_handler(sym, method)
         @handlers[sym] = method      
      end

      def call_handler(sym, *args)
        if handle?(sym)
          @handlers[sym].call(*args)
        else
          logger.warn "WARN: un-handled event: #{sym}"
        end
      end

      def handle?(sym)
        @handlers.has_key? sym
      end

      def add_request(req, timedout = 3)
        @pool[req.id] = {req: req, timestamp: Time.now, timedout: timedout}
        try_send_request(req)
      end

      def add_response(res)
        # find the same id
        req_data = @pool[res.id]
        if req_data
          @pool.delete(res.id)
          call_handler(:request_meet, req_data[:req], res)
        else
          # unmatched response
          # discard
          logger.warn "WARN: un-matched response (id=#{res.id}): #{res.inspect}"
        end
      end

      def update
        process_pending
        check_timedout
      end
      
      def check_timedout
        now = Time.now
        @pool.each do |id, req_data|
          if now - req_data[:timestamp] >= req_data[:timedout]
            # timedout
            @pool.delete(id)
            call_handler(:request_timedout, req_data[:req])
          end
        end
      end

      def process_pending
        @pool.each_value do |data|
          try_send_request(data[:req]) unless data[:req].sent?
        end
      end

      def try_send_request(req)
        if handle?(:send_request)
          req.sent! if call_handler(:send_request, req)
        end
      end
    end
  end
end


Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
tamashii-agent-0.1.11 lib/tamashii/agent/request_pool.rb
tamashii-agent-0.1.10 lib/tamashii/agent/request_pool.rb
tamashii-agent-0.1.9 lib/tamashii/agent/request_pool.rb
tamashii-agent-0.1.8 lib/tamashii/agent/request_pool.rb
tamashii-agent-0.1.7 lib/tamashii/agent/request_pool.rb