-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrb_call_server.rb
78 lines (66 loc) · 1.68 KB
/
rb_call_server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
require 'pp'
require 'msgpack'
require 'msgpack/rpc'
class RbCall
def initialize
@@variables = {}
end
def self.store_object( obj )
key = obj.object_id
if @@variables.has_key?( key )
@@variables[key][1] += 1
else
@@variables[key] = [obj, 1]
end
end
def self.find_object( obj_id )
@@variables[obj_id][0]
end
private
def send_impl( obj, method_name, args, kwargs)
# See https://bugs.ruby-lang.org/issues/12022
kwargs = kwargs.map {|k,v| [k.to_sym,v]}.to_h
if kwargs.empty?
ret = obj.send(method_name, *args)
else
ret = obj.send(method_name, *args, **kwargs)
end
ret
end
public
def send_method( objid, method_name, args = [], kwargs = {})
obj = self.class.find_object(objid)
send_impl( obj, method_name, args, kwargs )
end
def del_object( objid )
@@variables[objid][1] -= 1
if @@variables[objid][1] == 0
@@variables.delete(objid)
#$stderr.puts "deleted #{objid} #{@@variables.inspect}"
end
nil
end
def get_kernel
Kernel
end
end
Object.class_eval do
def self.from_msgpack_ext( data )
rb_cls, obj_id = MessagePack.unpack( data )
RbCall.find_object( obj_id )
end
def to_msgpack_ext
RbCall.store_object( self )
MessagePack.pack( [self.class.to_s, self.object_id] )
end
end
MessagePack::DefaultFactory.register_type(40, Object)
if $0 == __FILE__
svr = MessagePack::RPC::Server.new
svr.listen('localhost', 0, RbCall.new)
# a dirty hack to get the port number
port = svr.instance_variable_get(:@listeners).first.instance_variable_get(:@lsock).instance_variable_get(:@listen_socket).addr[1]
$stdout.puts port
$stdout.flush
svr.run
end