Sha256: 2ea15088b16679f6654e7d4655018276a2ce7685bab32edaf3341cc1ccfb5e02

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

require 'pb_actor/message'
require 'pb_actor/basic_proxy'
require 'pb_actor/async_proxy'
require 'pb_actor/future_proxy'

module PbActor
  class Proxy < BasicProxy
    def initialize origin
      @origin = origin
      pr, cw = IO.pipe
      cr, pw = IO.pipe
      @pid = fork do
        [pr, pw].each &:close
        @future_values = {}
        loop do
          type, id, method, *args = begin
                                      Message.recv cr
                                    rescue EOFError => e
                                      [:terminate]
                                    end
          case type
          when :async_method_call
            @origin.public_send method, *args
          when :future_method_call
            @future_values[id] = @origin.public_send method, *args
          when :future_value_get
            Message.send(if @future_values.has_key? id
              [:future_value, @future_values.delete(id)]
            else
              [:no_value]
            end, cw)
          when :terminate
            exit
          else
            raise "what happend!? receive #{type.inspect}"
          end
        end
      end
      [cr, cw].each &:close
      @rd = pr
      @wr = pw
      @alive = true
    end

    def method_missing method, *args, &blk
      super
      future.method_missing(method, *args).value
    end

    def async
      @async ||= AsyncProxy.new @origin, @pid, @wr, @rd
    end

    def future
      @future ||= FutureProxy.new @origin, @pid, @wr, @rd
    end

    def terminate
      raise DeadActorError, PbActor.dead_actor_msg unless alive?
      Message.send [:terminate], @wr
      Process.wait @pid
      nil
    rescue Errno::ECHILD => e
      raise DeadActorError, PbActor.dead_actor_msg
    end

    def terminate!
      raise DeadActorError, PbActor.dead_actor_msg unless alive?
      Process.kill "KILL", @pid
      Process.wait @pid
      nil
    rescue Errno::ECHILD, Errno::ESRCH => e
      raise DeadActorError, PbActor.dead_actor_msg
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pb_actor-0.0.5 lib/pb_actor/proxy.rb