ProjectSource

Async::Task

Encapsulates the state of a running task and it's result.

Signature

public

Since stable-v1.

Definitions

def self.yield

  • deprecated

Signature

deprecated

With no replacement.

Implementation

def self.yield
	Fiber.scheduler.transfer
end

def yield

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

Implementation

def yield
	Fiber.scheduler.yield
end

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

Create a new task.

Signature

parameter reactor Reactor

the reactor this task will run within.

parameter parent Task

the parent task.

Implementation

def initialize(parent = Task.current?, finished: nil, **options, &block)
	super(parent, **options)
	
	@status = :initialized
	@result = nil
	@finished = finished
	
	@block = block
	@fiber = nil
end

def sleep(duration = nil)

  • deprecated

Signature

deprecated

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

Implementation

def sleep(duration = nil)
	super
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.

Implementation

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

attr :fiber

attr :status

def run(*arguments)

Begin the execution of the task.

Implementation

def run(*arguments)
	if @status == :initialized
		@status = :running
		
		schedule(arguments)
	else
		raise RuntimeError, "Task already running!"
	end
end

def wait

Retrieve the current result of the task. Will cause the caller to wait until result is available.

Signature

returns Object

The final expression/result of the task's block.

Implementation

def wait
	raise "Cannot wait on own fiber" if Fiber.current.equal?(@fiber)
	
	if running?
		@finished ||= Condition.new
		@finished.wait
	end
	
	case @result
	when Exception
		raise @result
	else
		return @result
	end
end

attr :result

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

def stop(later = false)

Stop the task and all of its children.

Implementation

def stop(later = false)
	if self.stopped?
		# If we already stopped this task... don't try to stop it again:
		return
	end
	
	if self.running?
		if self.current?
			if later
				Fiber.scheduler.push Stop::Later.new(self)
			else
				raise Stop, "Stopping current task!"
			end
		elsif @fiber&.alive?
			begin
				Fiber.scheduler.raise(@fiber, Stop)
			rescue FiberError
				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

def self.current

Lookup the class Async::Task for the current fiber. Raise RuntimeError if none is available.

Signature

returns Task

Implementation

def self.current
	Thread.current[:async_task] or raise RuntimeError, "No async task available!"
end

def self.current?

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

Signature

returns Task | Nil

Implementation

def self.current?
	Thread.current[:async_task]
end

def running?

Check if the task is running.

Signature

returns Boolean

Implementation

def running?
	@status == :running
end

def finished?

Whether we can remove this node from the reactor graph.

Signature

returns Boolean

Implementation

def finished?
	super && @status != :running
end

def fail!(exception = nil, propagate = true)

This is a very tricky aspect of tasks to get right. I've modelled it after Thread but it's slightly different in that the exception can propagate back up through the reactor. If the user writes code which raises an exception, that exception should always be visible, i.e. cause a failure. If it's not visible, such code fails silently and can be very difficult to debug. As an explcit choice, the user can start a task which doesn't propagate exceptions. This only applies to StandardError and derived tasks. This allows tasks to internally capture their error state which is raised when invoking Task#result similar to how Thread#join works. This mode makes class Async::Task behave more like a promise, and you would need to ensure that someone calls Task#result otherwise you might miss important errors.

Implementation

def fail!(exception = nil, propagate = true)
	@status = :failed
	@result = exception
	
	if propagate
		raise
	elsif @finished.nil?
		# If no one has called wait, we log this as an error:
		Console.logger.error(self) {$!}
	else
		Console.logger.debug(self) {$!}
	end
end

def finish!

Finish the current task, and all bound bound IO objects.

Implementation

def finish!
	# Allow the fiber to be recycled.
	@fiber = nil
	
	# Attempt to remove this node from the task tree.
	consume
	
	# If this task was being used as a future, signal completion here:
	if @finished
		@finished.signal(@result)
	end
end

def set!

Set the current fiber's :async_task to this task.

Implementation

def set!
	# This is actually fiber-local:
	Thread.current[:async_task] = self
end

Discussion