Class: Async::Reactor

Inherits:
Node
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/async/reactor.rb

Overview

An asynchronous, cooperatively scheduled event reactor.

Instance Attribute Summary

Attributes inherited from Node

#annotation, #children, #parent

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#annotate, #consume, #description, #inspect, #print_hierarchy, #reap, #stop, #traverse

Constructor Details

#initialize(parent = nil, selector: self.class.selector, logger: nil) ⇒ Reactor

Returns a new instance of Reactor.



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/async/reactor.rb', line 73

def initialize(parent = nil, selector: self.class.selector, logger: nil)
	super(parent)
	
	@selector = selector
	@timers = Timers::Group.new
	@logger = logger
	
	@ready = []
	@running = []
	
	@interrupted = false
	@guard = Mutex.new
end

Class Method Details

.run(*arguments, **options, &block) ⇒ Object

The preferred method to invoke asynchronous behavior at the top level.

  • When invoked within an existing reactor task, it will run the given block asynchronously. Will return the task once it has been scheduled.
  • When invoked at the top level, will create and run a reactor, and invoke the block as an asynchronous task. Will block until the reactor finishes running.


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/async/reactor.rb', line 45

def self.run(*arguments, **options, &block)
	if current = Task.current?
		reactor = current.reactor
		
		return reactor.async(*arguments, **options, &block)
	else
		reactor = self.new(**options)
		
		begin
			return reactor.run(*arguments, &block)
		ensure
			reactor.close
		end
	end
end

.selectorObject



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/async/reactor.rb', line 61

def self.selector
	if backend = ENV['ASYNC_BACKEND']&.to_sym
		if NIO::Selector.backends.include?(backend)
			return NIO::Selector.new(backend)
		else
			warn "Could not find ASYNC_BACKEND=#{backend}!"
		end
	end
	
	return NIO::Selector.new
end

Instance Method Details

#<<(fiber) ⇒ Object

Schedule a fiber (or equivalent object) to be resumed on the next loop through the reactor.

Parameters:

  • fiber (#resume)

    The object to be resumed on the next iteration of the run-loop.



145
146
147
# File 'lib/async/reactor.rb', line 145

def << fiber
	@ready << fiber
end

#async(*arguments, **options) {|Task| ... } ⇒ Task

Start an asynchronous task within the specified reactor. The task will be executed until the first blocking call, at which point it will yield and and this method will return.

This is the main entry point for scheduling asynchronus tasks.

Yields:

  • (Task)

    Executed within the task.

Returns:

  • (Task)

    The task that was scheduled into the reactor.



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/async/reactor.rb', line 110

def async(*arguments, **options, &block)
	task = Task.new(self, **options, &block)
	
	# I want to take a moment to explain the logic of this.
	# When calling an async block, we deterministically execute it until the
	# first blocking operation. We don't *have* to do this - we could schedule
	# it for later execution, but it's useful to:
	# - Fail at the point of the method call where possible.
	# - Execute determinstically where possible.
	# - Avoid scheduler overhead if no blocking operation is performed.
	task.run(*arguments)
	
	# logger.debug "Initial execution of task #{fiber} complete (#{result} -> #{fiber.alive?})..."
	return task
end

#closevoid

This method returns an undefined value.

Stop each of the children tasks and close the selector.



244
245
246
247
248
249
250
# File 'lib/async/reactor.rb', line 244

def close
	self.stop
	
	# TODO Should we also clear all timers?
	@selector.close
	@selector = nil
end

#closed?Boolean

Check if the selector has been closed.

Returns:

  • (Boolean)


254
255
256
# File 'lib/async/reactor.rb', line 254

def closed?
	@selector.nil?
end

#finished?Boolean

Returns:

  • (Boolean)


156
157
158
159
# File 'lib/async/reactor.rb', line 156

def finished?
	# TODO I'm not sure if checking `@running.empty?` is really required.
	super && @ready.empty? && @running.empty?
end

#interruptObject

Interrupt the reactor at the earliest convenience. Can be called from a different thread safely.



134
135
136
137
138
139
140
141
# File 'lib/async/reactor.rb', line 134

def interrupt
	@guard.synchronize do
		unless @interrupted
			@interrupted = true
			@selector.wakeup
		end
	end
end

#loggerObject



87
88
89
# File 'lib/async/reactor.rb', line 87

def logger
	@logger ||= Console.logger
end

#register(io, interest, value = Fiber.current) ⇒ Object



126
127
128
129
130
131
# File 'lib/async/reactor.rb', line 126

def register(io, interest, value = Fiber.current)
	monitor = @selector.register(io, interest)
	monitor.value = value
	
	return monitor
end

#run(*arguments, &block) ⇒ Object

Run the reactor until either all tasks complete or #pause or Node#stop is invoked. Proxies arguments to #async immediately before entering the loop, if a block is provided.



227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/async/reactor.rb', line 227

def run(*arguments, &block)
	raise RuntimeError, 'Reactor has been closed' if @selector.nil?
	
	initial_task = self.async(*arguments, &block) if block_given?
	
	while self.run_once
		# Round and round we go!
	end
	
	return initial_task
ensure
	logger.debug(self) {"Exiting run-loop because #{$! ? $! : 'finished'}."}
end

#run_once(timeout = nil) ⇒ Boolean

Run one iteration of the event loop.

Parameters:

  • timeout (Float | nil) (defaults to: nil)

    the maximum timeout, or if nil, indefinite.

Returns:

  • (Boolean)

    whether there is more work to do.



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
# File 'lib/async/reactor.rb', line 164

def run_once(timeout = nil)
	logger.debug(self) {"@ready = #{@ready} @running = #{@running}"}
	
	if @ready.any?
		# running used to correctly answer on `finished?`, and to reuse Array object.
		@running, @ready = @ready, @running
		
		@running.each do |fiber|
			fiber.resume if fiber.alive?
		end
		
		@running.clear
	end
	
	if @ready.empty?
		interval = @timers.wait_interval
	else
		# if there are tasks ready to execute, don't sleep:
		interval = 0
	end
	
	# If there is no interval to wait (thus no timers), and no tasks, we could be done:
	if interval.nil?
		if self.finished?
			# If there is nothing to do, then finish:
			return false
		end
		
		# Allow the user to specify a maximum interval if we would otherwise be sleeping indefinitely:
		interval = timeout
	elsif interval < 0
		# We have timers ready to fire, don't sleep in the selctor:
		interval = 0
	elsif timeout and interval > timeout
		interval = timeout
	end
	
	logger.debug(self) {"Selecting with #{@children&.size} children with interval = #{interval ? interval.round(2) : 'infinite'}..."}
	if monitors = @selector.select(interval)
		monitors.each do |monitor|
			monitor.value.resume
		end
	end
	
	@timers.fire
	
	# We check and clear the interrupted flag here:
	if @interrupted
		@guard.synchronize do
			@interrupted = false
		end
		
		self.stop
		
		return false
	end
	
	return true
end

#sleep(duration) ⇒ Object

Put the calling fiber to sleep for a given ammount of time.

Parameters:

  • duration (Numeric)

    The time in seconds, to sleep for.



260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/async/reactor.rb', line 260

def sleep(duration)
	fiber = Fiber.current
	
	timer = self.after(duration) do
		if fiber.alive?
			fiber.resume
		end
	end
	
	Task.yield
ensure
	timer.cancel if timer
end

#stopped?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/async/reactor.rb', line 95

def stopped?
	@children.nil? || @children.empty?
end

#to_sObject



91
92
93
# File 'lib/async/reactor.rb', line 91

def to_s
	"\#<#{self.description} #{@children&.size || 0} children #{stopped? ? 'stopped' : 'running'}>"
end

#with_timeout(timeout, exception = TimeoutError) ⇒ Object

Invoke the block, but after the specified timeout, raise TimeoutError in any currenly blocking operation. If the block runs to completion before the timeout occurs or there are no non-blocking operations after the timeout expires, the code will complete without any exception.

Parameters:

  • duration (Numeric)

    The time in seconds, in which the task should complete.



277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/async/reactor.rb', line 277

def with_timeout(timeout, exception = TimeoutError)
	fiber = Fiber.current
	
	timer = self.after(timeout) do
		if fiber.alive?
			error = exception.new("execution expired")
			fiber.resume error
		end
	end
	
	yield timer
ensure
	timer.cancel if timer
end

#yield(fiber = Fiber.current) ⇒ Object

Yield the current fiber and resume it on the next iteration of the event loop.



150
151
152
153
154
# File 'lib/async/reactor.rb', line 150

def yield(fiber = Fiber.current)
	@ready << fiber
	
	Fiber.yield
end