Class: Async::Task

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

Overview

Represents a sequential unit of work, defined by a block, which is executed concurrently with other tasks. A task can be in one of the following states: initialized, running, completed, failed, or cancelled.

“‘mermaid stateDiagram-v2

*

–> Initialized

Initialized –> Running : Run

Running –> Completed : Return Value Running –> Failed : Exception

Completed –> [*] Failed –> [*]

Running –> Cancelled : Cancel Cancelled –> [*] Completed –> Cancelled : Cancel Failed –> Cancelled : Cancel Initialized –> Cancelled : Cancel “‘

Examples:

Creating a task that sleeps for 1 second.

require "async"
Async do |task|
	sleep(1)
end

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, #stop, #stopped?, #terminate, #transient=, #transient?, #traverse

Constructor Details

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

Create a new task.



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

def initialize(parent = Task.current?, finished: nil, **options, &block)
	# 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, and @block should be nil.
	# In a finished state, the @block should be nil, and the @fiber should be nil.
	@block = block
	@fiber = nil
	
	@promise = Promise.new
	
	# Handle finished: parameter for backward compatibility:
	case finished
	when false
		# `finished: false` suppresses warnings for expected task failures:
		@promise.suppress_warnings!
	when nil
		# `finished: nil` is the default, no special handling:
	else
		# All other `finished:` values are deprecated:
		warn("finished: argument with non-false value is deprecated and will be removed.", uplevel: 1, category: :deprecated) if $VERBOSE
	end
	
	@defer_cancel = nil
	
	# Call this after all state is initialized, as it may call `add_child` which will set the parent and make it visible to the scheduler.
	super(parent, **options)
end

Instance Attribute Details

#fiberObject (readonly)

Returns the value of attribute fiber.



162
163
164
# File 'lib/async/task.rb', line 162

def fiber
  @fiber
end

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



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

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.



436
437
438
# File 'lib/async/task.rb', line 436

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)


442
443
444
# File 'lib/async/task.rb', line 442

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.



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

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.



63
64
65
66
67
# File 'lib/async/task.rb', line 63

def self.yield
	warn("`Async::Task.yield` is deprecated with no replacement.", uplevel: 1, category: :deprecated) if $VERBOSE
	
	Fiber.scheduler.transfer
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


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

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.



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

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

#annotationObject



131
132
133
134
135
136
137
# File 'lib/async/task.rb', line 131

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:



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/async/task.rb', line 246

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



113
114
115
# File 'lib/async/task.rb', line 113

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

#cancel(later = false, cause: $!) ⇒ Object

Cancel the task and all of its children.

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



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/async/task.rb', line 328

def cancel(later = false, cause: $!)
	# If no cause is given, we generate one from the current call stack:
	unless cause
		cause = Cancel::Cause.for("Cancelling task!")
	end
	
	if self.cancelled?
		# If the task is already cancelled, a `cancel` state transition re-enters the same state which is a no-op. However, we will also attempt to cancel any running children too. This can happen if the children did not cancel correctly the first time around. Doing this should probably be considered a bug, but it's better to be safe than sorry.
		return cancelled!
	end
	
	# If the fiber is alive, we need to cancel 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 cancel...
		if @defer_cancel == false
			# Don't cancel now... but update the state so we know we need to cancel later.
			@defer_cancel = cause
			return false
		end
		
		if self.current?
			# If the fiber is current, and later is `true`, we need to schedule the fiber to be cancelled later, as it's currently invoking `cancel`:
			if later
				# If the fiber is the current fiber and we want to cancel it later, schedule it:
				Fiber.scheduler.push(Cancel::Later.new(self, cause))
			else
				# Otherwise, raise the exception directly:
				raise Cancel, "Cancelling current task!", cause: cause
			end
		else
			# If the fiber is not curent, we can raise the exception directly:
			begin
				# There is a chance that this will cancel the fiber that originally called cancel. If that happens, the exception handling in `#cancelled` will rescue the exception and re-raise it later.
				Fiber.scheduler.raise(@fiber, Cancel, cause: cause)
			rescue FiberError
				# In some cases, this can cause a FiberError (it might be resumed already), so we schedule it to be cancelled later:
				Fiber.scheduler.push(Cancel::Later.new(self, cause))
			end
		end
	else
		# We are not running, but children might be, so transition directly into cancelled state:
		cancel!
	end
end

#cancel_deferred?Boolean

Returns:

  • (Boolean)


423
424
425
# File 'lib/async/task.rb', line 423

def cancel_deferred?
	!!@defer_cancel
end

#cancelled?Boolean

Returns:

  • (Boolean)


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

def cancelled?
	@promise.cancelled?
end

#complete?Boolean

Alias for #completed?.

Returns:

  • (Boolean)


197
198
199
# File 'lib/async/task.rb', line 197

def complete?
	self.completed?
end

#completed?Boolean

Returns:

  • (Boolean)


192
193
194
# File 'lib/async/task.rb', line 192

def completed?
	@promise.completed?
end

#current?Boolean

Returns:

  • (Boolean)


447
448
449
# File 'lib/async/task.rb', line 447

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

#defer_cancelObject

Defer the handling of cancel. During the execution of the given block, if a cancel 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_cancel block to ensure that the task is cancelled when the response is complete but not before.

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

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



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/async/task.rb', line 384

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

#defer_stop(&block) ⇒ Object

Deprecated.

Use #defer_cancel instead.

Backward compatibility alias for #defer_cancel.



418
419
420
# File 'lib/async/task.rb', line 418

def defer_stop(&block)
	defer_cancel(&block)
end

#failed?Boolean

Returns:

  • (Boolean)


182
183
184
# File 'lib/async/task.rb', line 182

def failed?
	@promise.failed?
end

#finished?Boolean

Whether we can remove this node from the reactor graph.

Returns:

  • (Boolean)


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

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



108
109
110
# File 'lib/async/task.rb', line 108

def reactor
	self.root
end

#resultObject

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



311
312
313
314
315
316
317
318
319
320
# File 'lib/async/task.rb', line 311

def result
	value = @promise.value
	
	# For backward compatibility, return nil for cancelled tasks:
	if @promise.cancelled?
		nil
	else
		value
	end
end

#run(*arguments) ⇒ Object

Begin the execution of the task.



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

def run(*arguments)
	# Move from initialized to running by clearing @block
	if block = @block
		@block = nil
		
		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.
			unless @promise.waiting?
				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)


177
178
179
# File 'lib/async/task.rb', line 177

def running?
	self.alive?
end

#sleep(duration = nil) ⇒ Object

Deprecated.

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



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

def sleep(duration = nil)
	Kernel.warn("`Async::Task#sleep` is deprecated, use `Kernel#sleep` instead.", uplevel: 1, category: :deprecated) if $VERBOSE
	
	super
end

#statusObject



202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/async/task.rb', line 202

def status
	case @promise.resolved
	when :cancelled
		:cancelled
	when :failed
		:failed
	when :completed
		:completed
	when nil
		self.running? ? :running : :initialized
	end
end

#stop_deferred?Boolean

Deprecated.

Use #cancel_deferred? instead.

Backward compatibility alias for #cancel_deferred?.

Returns:

  • (Boolean)


429
430
431
# File 'lib/async/task.rb', line 429

def stop_deferred?
	cancel_deferred?
end

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



202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/async/task.rb', line 202

def status
	case @promise.resolved
	when :cancelled
		:cancelled
	when :failed
		:failed
	when :completed
		:completed
	when nil
		self.running? ? :running : :initialized
	end
end

#to_sObject



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

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

#waitObject Also known as: join

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 cancelled, 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).



271
272
273
274
275
276
# File 'lib/async/task.rb', line 271

def wait(...)
	raise "Cannot wait on own fiber!" if Fiber.current.equal?(@fiber)
	
	# Wait for the task to complete:
	@promise.wait(...)
end

#wait_allObject

Wait on all non-transient children to complete, recursively, then wait on the task itself, if it is not the current task.

If any child task fails with an exception, that exception will be raised immediately, and remaining children may not be waited on.

Examples:

Waiting on all children.

Async do |task|
	child = task.async do
		sleep(0.01)
	end
	task.wait_all # Will wait on the child task.
end


296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/async/task.rb', line 296

def wait_all
	@children&.each do |child|
		# Skip transient tasks
		next if child.transient?
		
		child.wait_all
	end
	
	# Only wait on the task if we're not waiting on ourselves:
	unless self.current?
		return self.wait
	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.



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

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.



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

def yield
	Fiber.scheduler.yield
end