Class: Async::Task

Inherits:
Node
  • Object
show all
Defined in:
lib/async/task.rb

Defined Under Namespace

Classes: FinishedError

Instance Attribute Summary collapse

Attributes inherited from Node

#A useful identifier for the current node., #Optional list of children., #children, #head, #parent, #tail

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#The parent node.=, #children?, #consume, #description, #print_hierarchy, #root, #terminate, #transient=, #transient?, #traverse

Constructor Details

#initialize(parent = Task.current?, finished: nil, **options, &block) ⇒ Task

Create a new task.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/async/task.rb', line 80

def initialize(parent = Task.current?, finished: nil, **options, &block)
	super(parent, **options)
	
	# These instance variables are critical to the state of the task.
	# In the initialized state, the @block should be set, but the @fiber should be nil.
	# In the running state, the @fiber should be set.
	# In a finished state, the @block should be nil, and the @fiber should be nil.
	@block = block
	@fiber = nil
	
	@status = :initialized
	@result = nil
	@finished = finished
	
	@defer_stop = nil
end

Instance Attribute Details

#fiberObject (readonly)

Returns the value of attribute fiber.



150
151
152
# File 'lib/async/task.rb', line 150

def fiber
  @fiber
end

#resultObject (readonly)

Access the result of the task without waiting. May be nil if the task is not completed. Does not raise exceptions.



259
260
261
# File 'lib/async/task.rb', line 259

def result
  @result
end

#statusObject (readonly)

Returns the value of attribute status.



187
188
189
# File 'lib/async/task.rb', line 187

def status
  @status
end

#The fiber which is being used for the execution of this task.(fiberwhichisbeingused) ⇒ Object (readonly)



150
# File 'lib/async/task.rb', line 150

attr :fiber

Class Method Details

.currentObject

Lookup the Async::Task for the current fiber. Raise ‘RuntimeError` if none is available. @raises If task was not set! for the current fiber.



357
358
359
# File 'lib/async/task.rb', line 357

def self.current
	Fiber.current.async_task or raise RuntimeError, "No async task available!"
end

.current?Boolean

Check if there is a task defined for the current fiber.

Returns:

  • (Boolean)


363
364
365
# File 'lib/async/task.rb', line 363

def self.current?
	Fiber.current.async_task
end

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

Run the given block of code in a task, asynchronously, in the given scheduler.



71
72
73
74
75
# File 'lib/async/task.rb', line 71

def self.run(scheduler, *arguments, **options, &block)
	self.new(scheduler, **options, &block).tap do |task|
		task.run(*arguments)
	end
end

.yieldObject

Deprecated.

With no replacement.



66
67
68
# File 'lib/async/task.rb', line 66

def self.yield
	Fiber.scheduler.transfer
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


153
154
155
# File 'lib/async/task.rb', line 153

def alive?
	@fiber&.alive?
end

#annotate(annotation, &block) ⇒ Object

Annotate the task with a description.

This will internally try to annotate the fiber if it is running, otherwise it will annotate the task itself.



112
113
114
115
116
117
118
# File 'lib/async/task.rb', line 112

def annotate(annotation, &block)
	if @fiber
		@fiber.annotate(annotation, &block)
	else
		super
	end
end

#annotationObject



121
122
123
124
125
126
127
# File 'lib/async/task.rb', line 121

def annotation
	if @fiber
		@fiber.annotation
	else
		super
	end
end

#async(*arguments, **options, &block) ⇒ Object

Run an asynchronous task as a child of the current task.

Raises:



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/async/task.rb', line 219

def async(*arguments, **options, &block)
	raise FinishedError if self.finished?
	
	task = Task.new(self, **options, &block)
	
	# 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.
	#
	# There are different strategies (greedy vs non-greedy). We are currently using a greedy strategy.
	task.run(*arguments)
	
	return task
end

#backtrace(*arguments) ⇒ Object



103
104
105
# File 'lib/async/task.rb', line 103

def backtrace(*arguments)
	@fiber&.backtrace(*arguments)
end

#completed?Boolean Also known as: complete?

Returns:

  • (Boolean)


180
181
182
# File 'lib/async/task.rb', line 180

def completed?
	@status == :completed
end

#current?Boolean

Returns:

  • (Boolean)


368
369
370
# File 'lib/async/task.rb', line 368

def current?
	Fiber.current.equal?(@fiber)
end

#defer_stopObject

Defer the handling of stop. During the execution of the given block, if a stop is requested, it will be deferred until the block exits. This is useful for ensuring graceful shutdown of servers and other long-running tasks. You should wrap the response handling code in a defer_stop block to ensure that the task is stopped when the response is complete but not before.

You can nest calls to defer_stop, but the stop will only be deferred until the outermost block exits.

If stop is invoked a second time, it will be immediately executed.



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/async/task.rb', line 317

def defer_stop
	# Tri-state variable for controlling stop:
	# - nil: defer_stop has not been called.
	# - false: defer_stop has been called and we are not stopping.
	# - true: defer_stop has been called and we will stop when exiting the block.
	if @defer_stop.nil?
		begin
			# If we are not deferring stop already, we can defer it now:
			@defer_stop = false
			
			yield
		rescue Stop
			# If we are exiting due to a stop, we shouldn't try to invoke stop again:
			@defer_stop = nil
			raise
		ensure
			defer_stop = @defer_stop
			
			# We need to ensure the state is reset before we exit the block:
			@defer_stop = nil
			
			# If we were asked to stop, we should do so now:
			if defer_stop
				raise Stop, "Stopping current task (was deferred)!"
			end
		end
	else
		# If we are deferring stop already, entering it again is a no-op.
		yield
	end
end

#failed?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'lib/async/task.rb', line 170

def failed?
	@status == :failed
end

#finished?Boolean

Whether we can remove this node from the reactor graph.

Returns:

  • (Boolean)


159
160
161
162
# File 'lib/async/task.rb', line 159

def finished?
	# If the block is nil and the fiber is nil, it means the task has finished execution. This becomes true after `finish!` is called.
	super && @block.nil? && @fiber.nil?
end

#reactorObject



98
99
100
# File 'lib/async/task.rb', line 98

def reactor
	self.root
end

#run(*arguments) ⇒ Object

Begin the execution of the task.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/async/task.rb', line 192

def run(*arguments)
	if @status == :initialized
		@status = :running
		
		schedule do
			@block.call(self, *arguments)
		rescue => error
			# I'm not completely happy with this overhead, but the alternative is to not log anything which makes debugging extremely difficult. Maybe we can introduce a debug wrapper which adds extra logging.
			if @finished.nil?
				warn(self, "Task may have ended with unhandled exception.", exception: error)
			end
			
			raise
		end
	else
		raise RuntimeError, "Task already running!"
	end
end

#running?Boolean

Returns:

  • (Boolean)


165
166
167
# File 'lib/async/task.rb', line 165

def running?
	@status == :running
end

#sleep(duration = nil) ⇒ Object

Deprecated.

Prefer Kernel#sleep except when compatibility with ‘stable-v1` is required.



135
136
137
# File 'lib/async/task.rb', line 135

def sleep(duration = nil)
	super
end

#stop(later = false) ⇒ Object

Stop the task and all of its children.

If ‘later` is false, it means that `stop` has been invoked directly. When `later` is true, it means that `stop` is invoked by `stop_children` or some other indirect mechanism. In that case, if we encounter the “current” fiber, we can’t stop it right away, as it’s currently performing ‘#stop`. Stopping it immediately would interrupt the current stop traversal, so we need to schedule the stop to occur later.



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/async/task.rb', line 266

def stop(later = false)
	if self.stopped?
		# If the task is already stopped, a `stop` state transition re-enters the same state which is a no-op. However, we will also attempt to stop any running children too. This can happen if the children did not stop correctly the first time around. Doing this should probably be considered a bug, but it's better to be safe than sorry.
		return stopped!
	end
	
	# If the fiber is alive, we need to stop it:
	if @fiber&.alive?
		# As the task is now exiting, we want to ensure the event loop continues to execute until the task finishes.
		self.transient = false
		
		# If we are deferring stop...
		if @defer_stop == false
			# Don't stop now... but update the state so we know we need to stop later.
			@defer_stop = true
			return false
		end
		
		if self.current?
			# If the fiber is current, and later is `true`, we need to schedule the fiber to be stopped later, as it's currently invoking `stop`:
			if later
				# If the fiber is the current fiber and we want to stop it later, schedule it:
				Fiber.scheduler.push(Stop::Later.new(self))
			else
				# Otherwise, raise the exception directly:
				raise Stop, "Stopping current task!"
			end
		else
			# If the fiber is not curent, we can raise the exception directly:
			begin
				# There is a chance that this will stop the fiber that originally called stop. If that happens, the exception handling in `#stopped` will rescue the exception and re-raise it later.
				Fiber.scheduler.raise(@fiber, Stop)
			rescue FiberError => error
				# In some cases, this can cause a FiberError (it might be resumed already), so we schedule it to be stopped later:
				Fiber.scheduler.push(Stop::Later.new(self))
			end
		end
	else
		# We are not running, but children might be, so transition directly into stopped state:
		stop!
	end
end

#stop_deferred?Boolean

Returns:

  • (Boolean)


350
351
352
# File 'lib/async/task.rb', line 350

def stop_deferred?
	@defer_stop
end

#stopped?Boolean

Returns:

  • (Boolean)


175
176
177
# File 'lib/async/task.rb', line 175

def stopped?
	@status == :stopped
end

#The status of the execution of the task, one of `:initialized`, `:running`, `:complete`, `:stopped` or `:failed`.=(statusoftheexecutionofthetask, oneof`: initialized`, `: running`, `: complete`, `: stopped`) ⇒ Object



187
# File 'lib/async/task.rb', line 187

attr :status

#to_sObject



130
131
132
# File 'lib/async/task.rb', line 130

def to_s
	"\#<#{self.description} (#{@status})>"
end

#waitObject

Retrieve the current result of the task. Will cause the caller to wait until result is available. If the task resulted in an unhandled error (derived from ‘StandardError`), this will be raised. If the task was stopped, this will return `nil`.

Conceptually speaking, waiting on a task should return a result, and if it throws an exception, this is certainly an exceptional case that should represent a failure in your program, not an expected outcome. In other words, you should not design your programs to expect exceptions from ‘#wait` as a normal flow control, and prefer to catch known exceptions within the task itself and return a result that captures the intention of the failure, e.g. a `TimeoutError` might simply return `nil` or `false` to indicate that the operation did not generate a valid result (as a timeout was an expected outcome of the internal operation in this case).



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/async/task.rb', line 242

def wait
	raise "Cannot wait on own fiber!" if Fiber.current.equal?(@fiber)
	
	# `finish!` will set both of these to nil before signaling the condition:
	if @block || @fiber
		@finished ||= Condition.new
		@finished.wait
	end
	
	if @status == :failed
		raise @result
	else
		return @result
	end
end

#with_timeout(duration, exception = TimeoutError, message = "execution expired", &block) ⇒ Object

Execute the given block of code, raising the specified exception if it exceeds the given duration during a non-blocking operation.



140
141
142
# File 'lib/async/task.rb', line 140

def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
	Fiber.scheduler.with_timeout(duration, exception, message, &block)
end

#yieldObject

Yield back to the reactor and allow other fibers to execute.



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

def yield
	Fiber.scheduler.yield
end