/
generic.rb
230 lines (187 loc) · 6.24 KB
/
generic.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# frozen_string_literal: true
# Copyright, 2017, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'async/wrapper'
require 'forwardable'
module Async
module IO
# The default block size for IO buffers. Defaults to 64KB (typical pipe buffer size).
BLOCK_SIZE = ENV.fetch('ASYNC_IO_BLOCK_SIZE', 1024*64).to_i
# The maximum read size when appending to IO buffers. Defaults to 8MB.
MAXIMUM_READ_SIZE = ENV.fetch('ASYNC_IO_MAXIMUM_READ_SIZE', BLOCK_SIZE * 128).to_i
# Convert a Ruby ::IO object to a wrapped instance:
def self.try_convert(io, &block)
if wrapper_class = Generic::WRAPPERS[io.class]
wrapper_class.new(io, &block)
else
raise ArgumentError.new("Unsure how to wrap #{io.class}!")
end
end
def self.pipe
::IO.pipe.map(&Generic.method(:new))
end
# Represents an asynchronous IO within a reactor.
class Generic < Wrapper
extend Forwardable
WRAPPERS = {}
class << self
# @!macro [attach] wrap_blocking_method
# @method $1
# Invokes `$2` on the underlying {io}. If the operation would block, the current task is paused until the operation can succeed, at which point it's resumed and the operation is completed.
def wrap_blocking_method(new_name, method_name, invert: true, &block)
if block_given?
define_method(new_name, &block)
else
define_method(new_name) do |*args|
async_send(method_name, *args)
end
end
if invert
# We wrap the original _nonblock method, ignoring options.
define_method(method_name) do |*args, exception: false|
async_send(method_name, *args)
end
end
end
attr :wrapped_klass
def wraps(klass, *additional_methods)
@wrapped_klass = klass
WRAPPERS[klass] = self
# These are methods implemented by the wrapped class, that we aren't overriding, that may be of interest:
# fallback_methods = klass.instance_methods(false) - instance_methods
# puts "Forwarding #{klass} methods #{fallback_methods} to @io"
def_delegators :@io, *additional_methods
end
# Instantiate a wrapped instance of the class, and optionally yield it to a given block, closing it afterwards.
def wrap(*args)
wrapper = self.new(@wrapped_klass.new(*args))
return wrapper unless block_given?
begin
yield wrapper
ensure
wrapper.close
end
end
end
wraps ::IO, :external_encoding, :internal_encoding, :autoclose?, :autoclose=, :pid, :stat, :binmode, :flush, :set_encoding, :set_encoding_by_bom, :to_io, :to_i, :reopen, :fileno, :fsync, :fdatasync, :sync, :sync=, :tell, :seek, :rewind, :pos, :pos=, :eof, :eof?, :close_on_exec?, :close_on_exec=, :closed?, :close_read, :close_write, :isatty, :tty?, :binmode?, :sysseek, :advise, :ioctl, :fcntl, :nread, :ready?, :pread, :pwrite, :pathconf
# Read the specified number of bytes from the input stream. This is fast path.
# @example
# data = io.sysread(512)
wrap_blocking_method :sysread, :read_nonblock
alias readpartial read_nonblock
# Read `length` bytes of data from the underlying I/O. If length is unspecified, read everything.
def read(length = nil, buffer = nil)
if buffer
buffer.clear
else
buffer = String.new
end
if length
return "" if length <= 0
# Fast path:
if buffer = self.sysread(length, buffer)
# Slow path:
while buffer.bytesize < length
# Slow path:
if chunk = self.sysread(length - buffer.bytesize)
buffer << chunk
else
break
end
end
return buffer
else
return nil
end
else
buffer = self.sysread(BLOCK_SIZE, buffer)
while chunk = self.sysread(BLOCK_SIZE)
buffer << chunk
end
return buffer
end
end
# Write entire buffer to output stream. This is fast path.
# @example
# io.syswrite("Hello World")
wrap_blocking_method :syswrite, :write_nonblock
def write(buffer)
# Fast path:
written = self.syswrite(buffer)
remaining = buffer.bytesize - written
while remaining > 0
# Slow path:
length = self.syswrite(buffer.byteslice(written, remaining))
remaining -= length
written += length
end
return written
end
def << buffer
write(buffer)
return self
end
def dup
super.tap do |copy|
copy.timeout = self.timeout
end
end
def wait(timeout = self.timeout, mode = :read)
case mode
when :read
wait_readable(timeout)
when :write
wait_writable(timeout)
else
wait_any(:rw, timeout)
end
rescue TimeoutError
return nil
end
def nonblock
true
end
def nonblock= value
true
end
def nonblock?
true
end
def connected?
!@io.closed?
end
attr_accessor :timeout
protected
def async_send(*arguments, timeout: self.timeout)
while true
result = @io.__send__(*arguments, exception: false)
case result
when :wait_readable
wait_readable(timeout)
when :wait_writable
wait_writable(timeout)
else
return result
end
end
end
end
end
end