wasm_drb 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0f735a776e83277fcb9b96925aa8ae44347840ad8e0b8fe9fae4532ba81affd9
4
+ data.tar.gz: 2abc1174c136cc8f0d77d766e127ac6c7ed30ac91cb6793fe3d04ca0460cca0b
5
+ SHA512:
6
+ metadata.gz: 608e8b9cd41c683ab244229d30313f7b952f85c4c0331bb9662f3c9619b0930fcfadfd9018051fb62195c45dc10923c49e26261ae56d472546fa6bedb367c7d6
7
+ data.tar.gz: 68bd1c462ecf8579fbb22a61d923dc2a0388f279a63ab0364ea83aa376e33673623ca541a37a5c7ff564726be35b3b38900d500ab3d3b8edaee773e1a0d452e2
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.3.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 youchan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Wasm::Drb
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/wasm/drb`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/wasm-drb.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
data/lib/drb/drb.rb ADDED
@@ -0,0 +1,118 @@
1
+ module DRb
2
+ class DRbUnknownError < DRbError
3
+ def initialize(unknown)
4
+ @unknown = unknown
5
+ super(unknown.name)
6
+ end
7
+ attr_reader :unknown
8
+
9
+ def self._load(s)
10
+ Marshal::load(s)
11
+ end
12
+
13
+ def _dump(lv)
14
+ Marshal::dump(@unknown)
15
+ end
16
+ end
17
+
18
+ class DRbRemoteError < DRbError
19
+ def initialize(error)
20
+ @reason = error.class.to_s
21
+ super("#{error.message} (#{error.class})")
22
+ set_backtrace(error.backtrace)
23
+ end
24
+
25
+ attr_reader :reason
26
+ end
27
+
28
+ module DRbUndumped
29
+ def _dump(dummy)
30
+ raise TypeError, 'can\'t dump'
31
+ end
32
+ end
33
+
34
+ class DRbUnknown
35
+ def initialize(err, buf)
36
+ case err.to_s
37
+ when /uninitialized constant (\S+)/
38
+ @name = $1
39
+ when /undefined class\/module (\S+)/
40
+ @name = $1
41
+ else
42
+ @name = nil
43
+ end
44
+ @buf = buf
45
+ end
46
+
47
+ attr_reader :name
48
+ attr_reader :buf
49
+
50
+ def self._load(s)
51
+ begin
52
+ Marshal::load(s)
53
+ rescue NameError, ArgumentError
54
+ DRbUnknown.new($!, s)
55
+ end
56
+ end
57
+
58
+ def _dump(lv)
59
+ @buf
60
+ end
61
+
62
+ def reload
63
+ self.class._load(@buf)
64
+ end
65
+
66
+ def exception
67
+ DRbUnknownError.new(self)
68
+ end
69
+ end
70
+
71
+ class DRbArray
72
+ def initialize(ary)
73
+ @ary = ary.collect { |obj|
74
+ if obj.kind_of? DRbUndumped
75
+ DRbObject.new(obj)
76
+ else
77
+ begin
78
+ Marshal.dump(obj)
79
+ obj
80
+ rescue
81
+ DRbObject.new(obj)
82
+ end
83
+ end
84
+ }
85
+ end
86
+
87
+ def self._load(s)
88
+ Marshal::load(s)
89
+ end
90
+
91
+ def _dump(lv)
92
+ Marshal.dump(@ary)
93
+ end
94
+ end
95
+
96
+ def self.to_obj(ref)
97
+ DRbObject.id2ref[ref]
98
+ end
99
+
100
+ def self.to_id(obj)
101
+ obj.nil? ? nil : obj.__id__
102
+ end
103
+
104
+ def self.current_server
105
+ @callback_server
106
+ end
107
+
108
+ def self.start_service(uri)
109
+ @callback_server = DRbServer.new(uri, {})
110
+ end
111
+
112
+ def self.default_config
113
+ {
114
+ argc_limit: 256,
115
+ load_limit: 256 * 102400
116
+ }
117
+ end
118
+ end
@@ -0,0 +1,38 @@
1
+ module DRb
2
+ class DRbConn
3
+ POOL_SIZE = 16
4
+ @pool = {}
5
+
6
+ def self.open(remote_uri)
7
+ conn = @pool[remote_uri]
8
+ unless conn&.alive?
9
+ conn = self.new(remote_uri)
10
+ @pool[remote_uri] = conn
11
+ end
12
+
13
+ yield(conn)
14
+ end
15
+
16
+ def initialize(remote_uri)
17
+ @uri = remote_uri
18
+ @protocol = DRbProtocol.open(remote_uri, DRb::default_config)
19
+ end
20
+ attr_reader :uri
21
+
22
+ def send_message(ref, msg_id, arg, b, &callback)
23
+ @protocol.send_request(ref, msg_id, arg, b) do |stream|
24
+ callback.call(@protocol.recv_reply(stream))
25
+ end
26
+ end
27
+
28
+ def close
29
+ @protocol.close
30
+ @protocol = nil
31
+ end
32
+
33
+ def alive?
34
+ return false unless @protocol
35
+ @protocol.alive?
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,93 @@
1
+ module DRb
2
+ class DRbMessage
3
+ def initialize(config)
4
+ config = DRb.default_config.merge(config || {})
5
+ @load_limit = config[:load_limit]
6
+ @argc_limit = config[:argc_limit]
7
+ end
8
+
9
+ def dump(obj, error=false)
10
+ obj = make_proxy(obj, error) if obj.kind_of? DRbUndumped
11
+ begin
12
+ str = Marshal::dump(obj)
13
+ rescue
14
+ str = Marshal::dump(make_proxy(obj, error))
15
+ end
16
+ [str.size].pack('N') + str
17
+ end
18
+
19
+ def load(soc)
20
+ begin
21
+ sz = soc.read(4)
22
+ rescue
23
+ raise(DRbConnError, $!.message, $!.backtrace)
24
+ end
25
+
26
+ raise(DRbConnError, 'connection closed') if sz.nil?
27
+ raise(DRbConnError, 'premature header') if sz.size < 4
28
+
29
+ sz = sz.unpack('N')[0]
30
+
31
+ raise(DRbConnError, "too large packet #{sz}") if @load_limit < sz
32
+ begin
33
+ str = soc.read(sz)
34
+ rescue
35
+ raise(DRbConnError, $!.message, $!.backtrace)
36
+ end
37
+
38
+ raise(DRbConnError, 'connection closed') if str.nil?
39
+ raise(DRbConnError, 'premature marshal format(can\'t read)') if str.size < sz
40
+
41
+ Marshal::load(str)
42
+ end
43
+
44
+ def send_request(stream, ref, msg_id, arg, b)
45
+ ary = []
46
+ ary.push(dump(ref.__drbref))
47
+ ary.push(dump(msg_id))
48
+ ary.push(dump(arg.length))
49
+ arg.each do |e|
50
+ ary.push(dump(e))
51
+ end
52
+ ary.push(dump(b))
53
+ stream.write(ary.join(''))
54
+ rescue
55
+ raise(DRbConnError, $!.message, $!.backtrace)
56
+ end
57
+
58
+ def recv_request(stream)
59
+ ref = load(stream)
60
+ ro = DRb.to_obj(ref)
61
+ msg = load(stream)
62
+ argc = load(stream)
63
+ raise(DRbConnError, "too many arguments") if @argc_limit < argc
64
+ argv = Array.new(argc, nil)
65
+ argc.times do |n|
66
+ argv[n] = load(stream)
67
+ end
68
+ block = load(stream)
69
+ return ro, msg, argv, block
70
+ end
71
+
72
+ def send_reply(stream, succ, result)
73
+ stream.write(dump(succ) + dump(result, !succ))
74
+ rescue
75
+ raise(DRbConnError, $!.message, $!.backtrace)
76
+ end
77
+
78
+ def recv_reply(stream)
79
+ succ = load(stream)
80
+ result = load(stream)
81
+ [succ, result]
82
+ end
83
+
84
+ private
85
+ def make_proxy(obj, error=false)
86
+ if error
87
+ DRbRemoteError.new(obj)
88
+ else
89
+ DRbObject.new(obj)
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,181 @@
1
+ module DRb
2
+ class DRbObject
3
+ def self._load(s)
4
+ uri, ref = Marshal.load(s)
5
+ self.new_with(uri, ref)
6
+ rescue Exception => e
7
+ puts e.message
8
+ end
9
+
10
+ def self.new_with(uri, ref)
11
+ it = self.allocate
12
+ it.instance_variable_set(:@uri, uri)
13
+ it.instance_variable_set(:@ref, ref)
14
+ it
15
+ end
16
+
17
+ def self.new_with_uri(uri)
18
+ self.new(nil, uri)
19
+ end
20
+
21
+ def _dump(lv)
22
+ Marshal.dump([@uri, @ref])
23
+ end
24
+
25
+ def initialize(obj, uri=nil)
26
+ @uri = nil
27
+ @ref = nil
28
+ if obj.nil?
29
+ return if uri.nil?
30
+ @uri, option = DRbProtocol.uri_option(uri, DRb::default_config)
31
+ @ref = DRbURIOption.new(option) unless option.nil?
32
+ else
33
+ @uri = uri ? uri : DRb.current_server.uri
34
+ @ref = obj ? DRb.to_id(obj) : nil
35
+ DRbObject.id2ref[@ref] = obj
36
+ end
37
+ end
38
+
39
+ def __drburi
40
+ @uri
41
+ end
42
+
43
+ def __drbref
44
+ @ref
45
+ end
46
+
47
+ def self.id2ref
48
+ @id2ref ||= {}
49
+ end
50
+
51
+ def inspect
52
+ @ref && @ref.inspect
53
+ end
54
+
55
+ def respond_to?(msg_id, priv=false)
56
+ case msg_id
57
+ when :_dump
58
+ true
59
+ when :marshal_dump
60
+ false
61
+ else
62
+ false
63
+ end
64
+ end
65
+
66
+ class DRbPromise
67
+ class WrapedResolve
68
+ attr_reader :data
69
+
70
+ def initialize(resolve)
71
+ @resolve = resolve
72
+ end
73
+
74
+ def apply(data)
75
+ @data = data
76
+ @resolve.apply
77
+ end
78
+ end
79
+
80
+ class Outer
81
+ def initialize(block)
82
+ @inner_block = block
83
+ end
84
+
85
+ def wraped_resolve(resolve)
86
+ @wraped_resolve = WrapedResolve.new(resolve)
87
+ end
88
+
89
+ def block
90
+ Proc.new do |resolve|
91
+ @inner_block.call(wraped_resolve(resolve))
92
+ end
93
+ end
94
+
95
+ def data
96
+ @wraped_resolve.data
97
+ end
98
+ end
99
+
100
+ def initialize(&block)
101
+ @outer = Outer.new(block)
102
+ @promise = JS.global[:Promise].new(&@outer.block)
103
+ end
104
+
105
+ def then(&block)
106
+ inner_block = Proc.new do
107
+ block.call @outer.data
108
+ end
109
+ @promise.then(&inner_block)
110
+ end
111
+
112
+ def await
113
+ @promise.await
114
+ @outer.data
115
+ end
116
+ end
117
+
118
+ def method_missing(msg_id, *a, &b)
119
+ DRbPromise.new do |resolve|
120
+ DRbConn.open(@uri) do |conn|
121
+ conn.send_message(self, msg_id, a, b) do |succ, result|
122
+ if succ
123
+ resolve.apply result
124
+ elsif DRbUnknown === result
125
+ resolve.apply result
126
+ else
127
+ bt = self.class.prepare_backtrace(@uri, result)
128
+ result.set_backtrace(bt + caller)
129
+ resolve.apply result
130
+ conn.close
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+
137
+ def self.prepare_backtrace(uri, result)
138
+ prefix = "(#{uri}) "
139
+ bt = []
140
+ result.backtrace.each do |x|
141
+ break if /`__send__'$/ =~ x
142
+ if /^\(druby:\/\// =~ x
143
+ bt.push(x)
144
+ else
145
+ bt.push(prefix + x)
146
+ end
147
+ end
148
+ bt
149
+ end
150
+
151
+ def pretty_print(q)
152
+ q.pp_object(self)
153
+ end
154
+
155
+ def pretty_print_cycle(q)
156
+ q.object_address_group(self) {
157
+ q.breakable
158
+ q.text '...'
159
+ }
160
+ end
161
+ end
162
+
163
+ class DRbURIOption
164
+ def initialize(option)
165
+ @option = option.to_s
166
+ end
167
+ attr_reader :option
168
+ def to_s; @option; end
169
+
170
+ def ==(other)
171
+ return false unless DRbURIOption === other
172
+ @option == other.option
173
+ end
174
+
175
+ def hash
176
+ @option.hash
177
+ end
178
+
179
+ alias eql? ==
180
+ end
181
+ end
@@ -0,0 +1,54 @@
1
+ module DRb
2
+ module DRbProtocol
3
+ @protocol = [DRb::WebSocket] # default
4
+ end
5
+
6
+ module DRbProtocol
7
+ def add_protocol(proto)
8
+ @protocol.push(proto)
9
+ end
10
+ module_function :add_protocol
11
+
12
+ def open_server(uri, config)
13
+ @protocol.each do |proto|
14
+ begin
15
+ return proto.open_server(uri, config)
16
+ rescue DRbBadScheme
17
+ rescue DRbConnError
18
+ raise($!)
19
+ rescue
20
+ raise(DRbConnError, "#{uri} - #{$!.inspect}")
21
+ end
22
+ end
23
+ raise DRbBadURI, 'can\'t parse uri:' + uri
24
+ end
25
+ module_function :open_server
26
+
27
+ def open(uri, config)
28
+ @protocol.each do |proto|
29
+ begin
30
+ return proto.open(uri, config)
31
+ rescue DRbBadScheme
32
+ rescue DRbConnError => e
33
+ raise e
34
+ rescue => e
35
+ raise(DRbConnError, "#{uri} - #{e.message}")
36
+ end
37
+ end
38
+ raise DRbBadURI, 'can\'t parse uri:' + uri
39
+ end
40
+ module_function :open
41
+
42
+ def uri_option(uri, config)
43
+ @protocol.each do |proto|
44
+ begin
45
+ uri, opt = proto.uri_option(uri, config)
46
+ return uri, opt
47
+ rescue DRbBadScheme
48
+ end
49
+ end
50
+ raise DRbBadURI, 'can\'t parse uri:' + uri
51
+ end
52
+ module_function :uri_option
53
+ end
54
+ end
@@ -0,0 +1,35 @@
1
+ module DRb
2
+ class DRbServer
3
+ def initialize(uri, option)
4
+ @protocol = DRbProtocol.open_server(uri, option)
5
+ run
6
+ end
7
+
8
+ def uri
9
+ @protocol.uri
10
+ end
11
+
12
+ def run
13
+ @protocol.accept do |client|
14
+ run
15
+ begin
16
+ succ = false
17
+ invoke_method = WasmDRb::InvokeMethod.new(self, client)
18
+ succ, result = invoke_method.perform
19
+ print_error(result) unless succ
20
+ client.send_reply(succ, result)
21
+ rescue Exception => e
22
+ print_error(e)
23
+ ensure
24
+ client.close unless succ
25
+ break unless succ
26
+ end
27
+ end
28
+ end
29
+
30
+ def print_error(e)
31
+ puts e.message
32
+ p e.backtrace
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,215 @@
1
+ require_relative '../wasm_drb/websocket'
2
+ require_relative 'drb_message'
3
+
4
+ module DRb
5
+ module WebSocket
6
+ class SocketPool
7
+ attr_reader :uri, :ws
8
+
9
+ def initialize(uri, ws)
10
+ @uri = uri
11
+ @ws = ws
12
+ @handlers = {}
13
+
14
+ ws.onmessage do |event|
15
+ message_data = event.data.to_s
16
+ sender_id = message_data.slice(0, 36)
17
+ message = message_data.slice(36, message_data.length - 36)
18
+ @handlers.delete(sender_id).call(message)
19
+ end
20
+ end
21
+
22
+ def self.open(uri)
23
+ @sockets ||= {}
24
+ @sockets[uri] ||= new_connection(uri)
25
+ end
26
+
27
+ def self.new_connection(uri)
28
+ ws = WasmDRb::WebSocket.new(uri)
29
+
30
+ ws.onclose do
31
+ @sockets[uri] = new_connection(uri)
32
+ end
33
+
34
+ self.new(uri, ws)
35
+ end
36
+
37
+ def send(data, &block)
38
+ sender_id = JS.global[:crypto].randomUUID().to_s
39
+ @handlers[sender_id] = block
40
+ byte_data = sender_id.bytes + data.bytes
41
+
42
+ if @ws.connecting?
43
+ listener = @ws.onopen do
44
+ @ws.send(WasmDRb::ArrayBuffer.new(byte_data))
45
+ @ws.remove_event_listener('open', &listener)
46
+ end
47
+ else
48
+ @ws.send(WasmDRb::ArrayBuffer.new(byte_data))
49
+ end
50
+ end
51
+
52
+ def [](uri)
53
+ @sockets[uri].ws
54
+ end
55
+ end
56
+
57
+ class StrStream
58
+ def initialize(str='')
59
+ @buf = str
60
+ end
61
+ attr_reader :buf
62
+
63
+ def read(n)
64
+ begin
65
+ return @buf[0,n]
66
+ ensure
67
+ @buf = @buf[n, @buf.size - n]
68
+ end
69
+ end
70
+
71
+ def write(s)
72
+ @buf += s
73
+ end
74
+ end
75
+
76
+ def self.uri_option(uri, config)
77
+ return uri, nil
78
+ end
79
+
80
+ def self.open(uri, config)
81
+ unless uri =~ /^ws:\/\/(.*?):(\d+)(\/(.*))?$/
82
+ raise(DRbBadScheme, uri) unless uri =~ /^ws:/
83
+ raise(DRbBadURI, 'can\'t parse uri:' + uri)
84
+ end
85
+ ClientSide.new(uri, config)
86
+ end
87
+
88
+ def self.open_server(uri, config)
89
+ unless uri =~ /^ws:\/\/(.*?):(\d+)(\/(.*))?$/
90
+ raise(DRbBadScheme, uri) unless uri =~ /^ws:/
91
+ raise(DRbBadURI, 'can\'t parse uri:' + uri)
92
+ end
93
+
94
+ Server.new(uri, config)
95
+ end
96
+
97
+ class Server
98
+ attr_reader :uri
99
+
100
+ def initialize(uri, config)
101
+ uuid = JS.global[:crypto].randomUUID()
102
+ @uri = "#{uri}/#{uuid}"
103
+ @config = config
104
+ reconnect
105
+ end
106
+
107
+ def close
108
+ @ws.close
109
+ end
110
+
111
+ def reconnect
112
+ @ws.close if @ws
113
+
114
+ @ws = WasmDRb::WebSocket.new(@uri)
115
+
116
+ @ws.onclose do
117
+ reconnect
118
+ end
119
+
120
+ @ws.onmessage do |event|
121
+ message_data = event.data.to_s
122
+ sender_id = message_data.slice(0, 36)
123
+ message = message_data.slice(36, message_data.length - 36)
124
+ stream = StrStream.new(message)
125
+ server_side = ServerSide.new(stream, @config, uri)
126
+ @accepter.call server_side
127
+
128
+ send_data = sender_id.bytes.each_slice(2).map(&:first)
129
+ send_data += server_side.reply.bytes.each_slice(2).map(&:first)
130
+ @ws.send(WasmDRb::ArrayBuffer.new(send_data))
131
+ end
132
+ end
133
+
134
+ def accept(&block)
135
+ @accepter = block
136
+ end
137
+ end
138
+
139
+ class ServerSide
140
+ attr_reader :uri, :reply
141
+
142
+ def initialize(stream, config, uri)
143
+ @uri = uri
144
+ @config = config
145
+ @msg = DRbMessage.new(@config)
146
+ @req_stream = stream
147
+ end
148
+
149
+ def close
150
+ end
151
+
152
+ def alive?; false; end
153
+
154
+ def recv_request
155
+ begin
156
+ @msg.recv_request(@req_stream)
157
+ rescue
158
+ close
159
+ raise $!
160
+ end
161
+ end
162
+
163
+ def send_reply(succ, result)
164
+ begin
165
+ stream = StrStream.new
166
+ @msg.send_reply(stream, succ, result)
167
+ @reply = stream.buf
168
+ rescue
169
+ close
170
+ raise $!
171
+ end
172
+ end
173
+ end
174
+
175
+ class ClientSide
176
+ def initialize(uri, config)
177
+ @uri = uri
178
+ @pool = SocketPool.open(uri)
179
+ @res = nil
180
+ @config = config
181
+ @msg = DRbMessage.new(@config)
182
+ end
183
+
184
+ def alive?
185
+ !!@pool.ws && @pool.ws.open?
186
+ end
187
+
188
+ def close
189
+ end
190
+
191
+ def send_request(ref, msg_id, *arg, b, &block)
192
+ stream = StrStream.new
193
+ @msg.send_request(stream, ref, msg_id, *arg, b)
194
+ send(@uri, stream.buf, &block)
195
+ end
196
+
197
+ def recv_reply(reply_stream)
198
+ @msg.recv_reply(reply_stream)
199
+ end
200
+
201
+ def send(uri, data, &block)
202
+ @pool.send(data) do |message|
203
+ reply_stream = StrStream.new
204
+ reply_stream.write(message.to_s)
205
+
206
+ if @config[:load_limit] < reply_stream.buf.size
207
+ raise TypeError, 'too large packet'
208
+ end
209
+
210
+ block.call reply_stream
211
+ end
212
+ end
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,30 @@
1
+ require 'js'
2
+
3
+ module WasmDRb
4
+ class ArrayBuffer
5
+ def initialize(data)
6
+ @js_array = JS.global[:Uint8Array].new(data)
7
+ end
8
+
9
+ def self.from_array(arr)
10
+ @js_array = JS.global[:Uint8Array].new(arr.length)
11
+ arr.each_with_index do |i, v|
12
+ @js_array[i] = v
13
+ end
14
+ end
15
+
16
+ def buffer
17
+ @js_array[:buffer]
18
+ end
19
+
20
+ def length
21
+ @js_array[:length]
22
+ end
23
+
24
+ def to_s
25
+ @js_array.to_a.map do |d|
26
+ d.to_i.chr
27
+ end.join
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,86 @@
1
+ module WasmDRb
2
+ class InvokeMethod
3
+ def initialize(drb_server, client)
4
+ @drb_server = drb_server
5
+ @client = client
6
+ end
7
+
8
+ def perform
9
+ @result = nil
10
+ @succ = false
11
+
12
+ setup_message
13
+
14
+ if @block
15
+ @result = perform_with_block
16
+ else
17
+ @result = perform_without_block
18
+ end
19
+
20
+ @succ = true
21
+ if @msg_id == :to_ary && @result.class == Array
22
+ @result = DRbArray.new(@result)
23
+ end
24
+ return @succ, @result
25
+ rescue StandardError, ScriptError, Interrupt
26
+ @result = $!
27
+ return @succ, @result
28
+ end
29
+
30
+ private
31
+ def init_with_client
32
+ obj, msg, argv, block = @client.recv_request
33
+ @obj = obj
34
+ @msg_id = msg.intern
35
+ @argv = argv
36
+ @block = block
37
+ end
38
+
39
+
40
+ def any_to_s(obj)
41
+ obj.to_s + ":#{obj.class}"
42
+ rescue
43
+ "#<#{obj.class}:0x#{obj.__id__.to_s(16)}>"
44
+ end
45
+
46
+ def check_insecure_method(obj, msg_id)
47
+ return true if Proc === obj && msg_id == :__drb_yield
48
+ raise(ArgumentError, "#{any_to_s(msg_id)} is not a symbol") unless Symbol == msg_id.class
49
+ raise(SecurityError, "insecure method `#{msg_id}'") if insecure_method?(msg_id)
50
+
51
+ if obj.private_methods.include?(msg_id)
52
+ desc = any_to_s(obj)
53
+ raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
54
+ else
55
+ true
56
+ end
57
+ end
58
+
59
+ def setup_message
60
+ init_with_client
61
+ check_insecure_method(@obj, @msg_id)
62
+ end
63
+
64
+ def perform_without_block
65
+ if Proc === @obj && @msg_id == :__drb_yield
66
+ if @argv.size == 1
67
+ ary = @argv
68
+ else
69
+ ary = [@argv]
70
+ end
71
+ ary.collect(&@obj)[0]
72
+ else
73
+ @obj.__send__(@msg_id, *@argv)
74
+ end
75
+ end
76
+
77
+ INSECURE_METHOD = [
78
+ :__send__
79
+ ]
80
+
81
+ # Has a method been included in the list of insecure methods?
82
+ def insecure_method?(msg_id)
83
+ INSECURE_METHOD.include?(msg_id)
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wasm
4
+ module Drb
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,80 @@
1
+ require 'js'
2
+ require_relative 'array_buffer'
3
+
4
+ module WasmDRb
5
+ class WebSocket
6
+ def initialize(uri)
7
+ @js_ws = JS.global[:WebSocket].new(uri)
8
+ @js_ws[:binaryType] = 'arraybuffer'
9
+
10
+ @listeners = {}
11
+ end
12
+
13
+ def onmessage(&block)
14
+ listener = Proc.new {|event| yield MessageEvent.new(event) if self.open? }
15
+ @listeners[block] = [:message, listener]
16
+ add_event_listener('message', &listener)
17
+ end
18
+
19
+ def onopen(&block)
20
+ listener = Proc.new {|_event| yield }
21
+ @listeners[block] = [:open, listener]
22
+ add_event_listener('open', &listener)
23
+ listener
24
+ end
25
+
26
+ def onclose(&block)
27
+ listener = Proc.new {|_event| yield }
28
+ @listeners[block] = [:close, listener]
29
+ add_event_listener('close', &listener)
30
+ end
31
+
32
+ def off handler
33
+ remove_event_listener(*@listeners[handler])
34
+ end
35
+
36
+ def connecting?
37
+ @js_ws[:readyState] == 0
38
+ end
39
+
40
+ def open?
41
+ @js_ws[:readyState] == 1
42
+ end
43
+
44
+ def closing?
45
+ @js_ws[:readyState] == 2
46
+ end
47
+
48
+ def closed?
49
+ @js_ws[:readyState] == 3
50
+ end
51
+
52
+ # alias_native
53
+ def close
54
+ @js_ws.close
55
+ end
56
+
57
+ def send mesg
58
+ @js_ws.call(:send, mesg.buffer)
59
+ end
60
+
61
+ def add_event_listener(type, &listener)
62
+ @js_ws.addEventListener(type, &listener)
63
+ end
64
+
65
+ def remove_event_listener(type, &listener)
66
+ @js_ws.removeEventListener(type, &listener)
67
+ end
68
+
69
+ class MessageEvent
70
+ def initialize(js_event)
71
+ @js_event = js_event
72
+ end
73
+
74
+ def data
75
+ ArrayBuffer.new(@js_event[:data])
76
+ end
77
+ end
78
+
79
+ end
80
+ end
data/lib/wasm_drb.rb ADDED
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "wasm_drb/version"
4
+
5
+ module WasmDRb
6
+ end
7
+
8
+ module DRb
9
+ class DRbError < RuntimeError; end
10
+ class DRbConnError < DRbError; end
11
+ class DRbServerNotFound < DRbError; end
12
+ class DRbBadURI < DRbError; end
13
+ class DRbBadScheme < DRbError; end
14
+ end
15
+
16
+ require_relative 'wasm_drb/websocket'
17
+ require_relative 'wasm_drb/invoke_method'
18
+ require_relative 'wasm_drb/array_buffer'
19
+
20
+ require_relative 'drb/websocket'
21
+ require_relative 'drb/drb_protocol'
22
+ require_relative 'drb/drb_conn'
23
+ require_relative 'drb/drb_object'
24
+ require_relative 'drb/drb_message'
25
+ require_relative 'drb/drb_server'
26
+ require_relative 'drb/drb'
data/sig/wasm/drb.rbs ADDED
@@ -0,0 +1,6 @@
1
+ module Wasm
2
+ module Drb
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wasm_drb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - youchan
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-03-10 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ruby_wasm
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.7'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '2.7'
26
+ - !ruby/object:Gem::Dependency
27
+ name: js
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '2.7'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '2.7'
40
+ description: A dRuby implementation for ruby.wasm.
41
+ email:
42
+ - youchan01@gmail.com
43
+ executables: []
44
+ extensions: []
45
+ extra_rdoc_files: []
46
+ files:
47
+ - ".ruby-version"
48
+ - LICENSE.txt
49
+ - README.md
50
+ - Rakefile
51
+ - lib/drb/drb.rb
52
+ - lib/drb/drb_conn.rb
53
+ - lib/drb/drb_message.rb
54
+ - lib/drb/drb_object.rb
55
+ - lib/drb/drb_protocol.rb
56
+ - lib/drb/drb_server.rb
57
+ - lib/drb/websocket.rb
58
+ - lib/wasm_drb.rb
59
+ - lib/wasm_drb/array_buffer.rb
60
+ - lib/wasm_drb/invoke_method.rb
61
+ - lib/wasm_drb/version.rb
62
+ - lib/wasm_drb/websocket.rb
63
+ - sig/wasm/drb.rbs
64
+ homepage: https://github.com/youchan/wasm_drb
65
+ licenses:
66
+ - MIT
67
+ metadata:
68
+ allowed_push_host: https://rubygems.org
69
+ homepage_uri: https://github.com/youchan/wasm_drb
70
+ source_code_uri: https://github.com/youchan/wasm_drb
71
+ changelog_uri: https://github.com/youchan/wasm_drb/CHANGELOG.md
72
+ rdoc_options: []
73
+ require_paths:
74
+ - lib
75
+ required_ruby_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: 3.2.0
80
+ required_rubygems_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ requirements: []
86
+ rubygems_version: 3.6.5
87
+ specification_version: 4
88
+ summary: A dRuby implementation for ruby.wasm.
89
+ test_files: []