class Async::Task

@public Since *Async v1*.
end
sleep(1)
Async do |task|
require “async”
@example Creating a task that sleeps for 1 second.
“‘
Initialized –> Cancelled : Cancel
Failed –> Cancelled : Cancel
Completed –> Cancelled : Cancel
Cancelled –> [*]
Running –> Cancelled : Cancel
Failed –> [*]
Completed –> [*]
Running –> Failed : Exception
Running –> Completed : Return Value
Initialized –> Running : Run<br> –> Initialized
stateDiagram-v2
“`mermaid
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`.

def self.current

@raises[RuntimeError] If task was not {set!} for the current fiber.
@returns [Task]
Lookup the {Task} for the current fiber. Raise `RuntimeError` if none is available.
def self.current
	Fiber.current.async_task or raise RuntimeError, "No async task available!"
end

def self.current?

@returns [Interface(:async) | Nil]
Check if there is a task defined for the current fiber.
def self.current?
	Fiber.current.async_task
end

def self.run(scheduler, *arguments, **options, &block)

Run the given block of code in a task, asynchronously, in the given scheduler.
def self.run(scheduler, *arguments, **options, &block)
	self.new(scheduler, **options, &block).tap do |task|
		task.run(*arguments)
	end
end

def self.yield

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

def alive?

@returns [Boolean] Whether the internal fiber is alive, i.e. it is actively executing.
def alive?
	@fiber&.alive?
end

def annotate(annotation, &block)

@parameter annotation [String] The description to annotate the task with.

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

Annotate the task with a description.
def annotate(annotation, &block)
	if @fiber
		@fiber.annotate(annotation, &block)
	else
		super
	end
end

def annotation

@returns [Object] The annotation of the task.
def annotation
	if @fiber
		@fiber.annotation
	else
		super
	end
end

def async(*arguments, **options, &block)

@returns [Task] The child task.
@raises [FinishedError] If the task has already finished.
@yields {|task| ...} in the context of the new task.

@asynchronous May context switch immediately to the new task.
@public Since *Async v1*.

Run an asynchronous task as a child of the current task.
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

def backtrace(*arguments)

@returns [Array(Thread::Backtrace::Location) | Nil] The backtrace of the task, if available.
def backtrace(*arguments)
	@fiber&.backtrace(*arguments)
end

def cancel(later = false, cause: $!)

@parameter cause [Exception] The cause of the cancel operation.
@parameter later [Boolean] Whether to cancel the task later, or immediately.

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.

Cancel the task and all of its children.
def cancel(later = false, cause: $!)
	# On affected Ruby versions, `Thread#kill` exposes the internal `TAG_FATAL` value through `$!`, which is not a valid exception cause:
	unless cause.is_a?(::Exception)
		cause = nil
	end
	
	# 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!(cause)
	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!(cause)
	end
end

def cancel!(cause = $!)

def cancel!(cause = $!)
	cancelled!(cause)
	
	finish!
end

def cancel_deferred?

@returns [Boolean] Whether cancel has been deferred.
def cancel_deferred?
	!!@defer_cancel
end

def cancelled!(cause = $!)

def cancelled!(cause = $!)
	# Console.info(self, status:) {"Task #{self} was cancelled with #{@children&.size.inspect} children!"}
	
	# Cancel the promise, specify nil here so that no exception is raised when waiting on the promise:
	@promise.cancel(nil)
	
	cancelled = false
	
	begin
		# We are not running, but children might be so we should stop them:
		stop_children(true, cause: cause)
	rescue Cancel => exception
		cancelled = true
		cause ||= exception.cause || exception
		# If we are cancelling children, and one of them tries to cancel the current task, we should ignore it. We will be cancelled later.
		retry
	end
	
	if cancelled
		raise Cancel, "Cancelling current task!", cause: cause
	end
end

def cancelled?

@returns [Boolean] Whether the task has been cancelled.
def cancelled?
	@promise.cancelled?
end

def complete?

Alias for {#completed?}.
def complete?
	self.completed?
end

def completed!(result)

State transition into the completed state.
def completed!(result)
	# Resolve the promise with the result:
	@promise.resolve(result)
end

def completed?

@returns [Boolean] Whether the task has completed execution and generated a result.
def completed?
	@promise.completed?
end

def current?

@returns [Boolean] Whether this task is the currently executing task.
def current?
	Fiber.current.equal?(@fiber)
end

def defer_cancel

@public Since *Async v1*.
@yields {} The block of code to execute.

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

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

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.
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

def defer_stop(&block)

Deprecated:
  • Use {#defer_cancel} instead.
def defer_stop(&block)
	defer_cancel(&block)
end

def failed!(exception = false)

State transition into the failed state.
def failed!(exception = false)
	# Reject the promise with the exception:
	@promise.reject(exception)
end

def failed?

@returns [Boolean] Whether the task failed with an exception.
def failed?
	@promise.failed?
end

def finish!

Finish the current task, moving any children to the parent.
def finish!
	# Break the cycle:
	@fiber&.async_task = nil
	
	# Don't hold references to the fiber or block after the task has finished:
	@fiber = nil
	@block = nil # If some how we went directly from initialized to finished.
	
	# Attempt to remove this node from the task tree.
	consume
end

def finished?

@returns [Boolean]
Whether we can remove this node from the reactor graph.
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

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

@parameter parent [Task] the parent task.
@parameter reactor [Reactor] the reactor this task will run within.
Create a new task.
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

def reactor

@returns [Scheduler] The scheduler for this task.
def reactor
	self.root
end

def result

Access the result of the task without waiting. May be nil if the task is not completed. Does not raise exceptions.
def result
	value = @promise.value
	
	# For backward compatibility, return nil for cancelled tasks:
	if @promise.cancelled?
		nil
	else
		value
	end
end

def run(*arguments)

@raises [RuntimeError] If the task is already running.

Begin the execution of the task.
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

def running?

@returns [Boolean] Whether the task is running.
def running?
	self.alive?
end

def schedule(&block)

def schedule(&block)
	@fiber = Fiber.new(annotation: self.annotation) do
		begin
			completed!(yield)
		rescue Cancel => exception
			cancelled!(exception.cause || exception)
		rescue StandardError => error
			failed!(error)
		rescue Exception => exception
			failed!(exception)
			
			# This is a critical failure, we should stop the reactor:
			raise
		ensure
			# Console.info(self) {"Task ensure $! = #{$!} with #{@children&.size.inspect} children!"}
			finish!
		end
	end
	
	@fiber.async_task = self
	
	(Fiber.scheduler || self.reactor).resume(@fiber)
end

def sleep(duration = nil)

Deprecated:
  • Prefer {Kernel#sleep} except when compatibility with `stable-v1` is required.
def sleep(duration = nil)
	Kernel.warn("`Async::Task#sleep` is deprecated, use `Kernel#sleep` instead.", uplevel: 1, category: :deprecated) if $VERBOSE
	
	super
end

def status

@attribute [Symbol] The status of the execution of the task, one of `:initialized`, `:running`, `:complete`, `:cancelled` or `:failed`.
def status
	case @promise.resolved
	when :cancelled
		:cancelled
	when :failed
		:failed
	when :completed
		:completed
	when nil
		self.running? ? :running : :initialized
	end
end

def stop!

def stop!
	cancel!
end

def stop_deferred?

Deprecated:
  • Use {#cancel_deferred?} instead.
def stop_deferred?
	cancel_deferred?
end

def stopped!

def stopped!
	cancelled!
end

def to_s

@returns [String] A description of the task and it's current status.
def to_s
	"\#<#{self.description} (#{self.status})>"
end

def wait(...)

@asynchronous This method is thread-safe.
@returns [Object] The final expression/result of the task's block.
@raises [RuntimeError] If the task's fiber is the current fiber.
@parameter timeout [Numeric] The maximum number of seconds to wait for the result before raising a `TimeoutError`, if specified.

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

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`.
def wait(...)
	raise "Cannot wait on own fiber!" if Fiber.current.equal?(@fiber)
	
	# Wait for the task to complete:
	@promise.wait(...)
end

def wait_all

Other tags:
    Example: Waiting on all children. -
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

def warn(...)

def warn(...)
	Console.warn(...)
end

def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)

Execute the given block of code, raising the specified exception if it exceeds the given duration during a non-blocking operation.
def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
	Fiber.scheduler.with_timeout(duration, exception, message, &block)
end

def yield

Yield back to the reactor and allow other fibers to execute.
def yield
	Fiber.scheduler.yield
end