1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 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 308 309 310 311 312 313 314 315 316 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 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 375 376 377 378 379 380 381 382 383 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
|
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2017-2025, by Samuel Williams.
# Copyright, 2017, by Kent Gruber.
# Copyright, 2017, by Devin Christensen.
# Copyright, 2020, by Patrik Wenger.
# Copyright, 2023, by Math Ieu.
# Copyright, 2025, by Shigeru Nakajima.
# Copyright, 2025, by Shopify Inc.
require "fiber"
require "console"
require_relative "node"
require_relative "condition"
require_relative "promise"
require_relative "stop"
Fiber.attr_accessor :async_task
module Async
# Raised if a timeout occurs on a specific Fiber. Handled gracefully by `Task`.
# @public Since *Async v1*.
class TimeoutError < StandardError
# Create a new timeout error.
#
# @parameter message [String] The error message.
def initialize(message = "execution expired")
super
end
end
# 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`, `cancelled` or `stopped`.
#
# ```mermaid
# stateDiagram-v2
# [*] --> Initialized
# Initialized --> Running : Run
#
# Running --> Completed : Return Value
# Running --> Failed : Exception
#
# Completed --> [*]
# Failed --> [*]
#
# Running --> Stopped : Stop
# Stopped --> [*]
# Completed --> Stopped : Stop
# Failed --> Stopped : Stop
# Initialized --> Stopped : Stop
# ```
#
# @example Creating a task that sleeps for 1 second.
# require "async"
# Async do |task|
# sleep(1)
# end
#
# @public Since *Async v1*.
class Task < Node
# Raised when a child task is created within a task that has finished execution.
class FinishedError < RuntimeError
# Create a new finished error.
#
# @parameter message [String] The error message.
def initialize(message = "Cannot create child task within a task that has finished execution!")
super
end
end
# @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
# 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
# Create a new task.
# @parameter reactor [Reactor] the reactor this task will run within.
# @parameter parent [Task] the parent 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_stop = 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
# @returns [Scheduler] The scheduler for this task.
def reactor
self.root
end
# @returns [Array(Thread::Backtrace::Location) | Nil] The backtrace of the task, if available.
def backtrace(*arguments)
@fiber&.backtrace(*arguments)
end
# 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.
#
# @parameter annotation [String] The description to annotate the task with.
def annotate(annotation, &block)
if @fiber
@fiber.annotate(annotation, &block)
else
super
end
end
# @returns [Object] The annotation of the task.
def annotation
if @fiber
@fiber.annotation
else
super
end
end
# @returns [String] A description of the task and it's current status.
def to_s
"\#<#{self.description} (#{self.status})>"
end
# @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
# 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
# Yield back to the reactor and allow other fibers to execute.
def yield
Fiber.scheduler.yield
end
# @attribute [Fiber] The fiber which is being used for the execution of this task.
attr :fiber
# @returns [Boolean] Whether the internal fiber is alive, i.e. it is actively executing.
def alive?
@fiber&.alive?
end
# Whether we can remove this node from the reactor graph.
# @returns [Boolean]
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
# @returns [Boolean] Whether the task is running.
def running?
self.alive?
end
# @returns [Boolean] Whether the task failed with an exception.
def failed?
@promise.failed?
end
# @returns [Boolean] Whether the task has been stopped.
def stopped?
@promise.cancelled?
end
# @returns [Boolean] Whether the task has completed execution and generated a result.
def completed?
@promise.completed?
end
# Alias for {#completed?}.
def complete?
self.completed?
end
# @attribute [Symbol] The status of the execution of the task, one of `:initialized`, `:running`, `:complete`, `:stopped` or `:failed`.
def status
case @promise.resolved
when :cancelled
:stopped
when :failed
:failed
when :completed
:completed
when nil
self.running? ? :running : :initialized
end
end
# Begin the execution of the task.
#
# @raises [RuntimeError] If the task is already running.
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
# Run an asynchronous task as a child of the current task.
#
# @public Since *Async v1*.
# @asynchronous May context switch immediately to the new task.
#
# @yields {|task| ...} in the context of the new task.
# @raises [FinishedError] If the task has already finished.
# @returns [Task] The child 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
# 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).
#
# @raises [RuntimeError] If the task's fiber is the current fiber.
# @returns [Object] The final expression/result of the task's block.
# @asynchronous This method is thread-safe.
def wait
raise "Cannot wait on own fiber!" if Fiber.current.equal?(@fiber)
# Wait for the task to complete - Promise handles all the complexity:
begin
@promise.wait
rescue Promise::Cancel
# For backward compatibility, stopped tasks return nil:
return nil
end
end
# For compatibility with `Thread#join` and similar interfaces.
alias join wait
# 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.
#
# @example 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
#
# @raises [StandardError] If any child task failed with an exception, that exception will be raised.
# @returns [Object | Nil] The final expression/result of the task's block, or nil if called from within the task.
# @asynchronous This method is thread-safe.
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
# 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 stopped tasks:
if @promise.cancelled?
nil
else
value
end
end
# 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.
#
# @parameter later [Boolean] Whether to stop the task later, or immediately.
# @parameter cause [Exception] The cause of the stop operation.
def stop(later = false, cause: $!)
# If no cause is given, we generate one from the current call stack:
unless cause
cause = Stop::Cause.for("Stopping task!")
end
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 = cause
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, cause))
else
# Otherwise, raise the exception directly:
raise Stop, "Stopping 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 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, cause: cause)
rescue FiberError
# 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, cause))
end
end
else
# We are not running, but children might be, so transition directly into stopped state:
stop!
end
end
# 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.
#
# @yields {} The block of code to execute.
# @public Since *Async v1*.
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)!", cause: defer_stop
end
end
else
# If we are deferring stop already, entering it again is a no-op.
yield
end
end
# @returns [Boolean] Whether stop has been deferred.
def stop_deferred?
!!@defer_stop
end
# Lookup the {Task} for the current fiber. Raise `RuntimeError` if none is available.
# @returns [Task]
# @raises[RuntimeError] If task was not {set!} for the current fiber.
def self.current
Fiber.current.async_task or raise RuntimeError, "No async task available!"
end
# Check if there is a task defined for the current fiber.
# @returns [Interface(:async) | Nil]
def self.current?
Fiber.current.async_task
end
# @returns [Boolean] Whether this task is the currently executing task.
def current?
Fiber.current.equal?(@fiber)
end
private
def warn(...)
Console.warn(...)
end
# Finish the current task, moving any children to the parent.
def finish!
# 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
# State transition into the completed state.
def completed!(result)
# Resolve the promise with the result:
@promise.resolve(result)
end
# State transition into the failed state.
def failed!(exception = false)
# Reject the promise with the exception:
@promise.reject(exception)
end
def stopped!
# Console.info(self, status:) {"Task #{self} was stopped with #{@children&.size.inspect} children!"}
# Cancel the promise:
@promise.cancel
stopped = false
begin
# We are not running, but children might be so we should stop them:
stop_children(true)
rescue Stop
stopped = true
# If we are stopping children, and one of them tries to stop the current task, we should ignore it. We will be stopped later.
retry
end
if stopped
raise Stop, "Stopping current task!"
end
end
def stop!
stopped!
finish!
end
def schedule(&block)
@fiber = Fiber.new(annotation: self.annotation) do
begin
completed!(yield)
rescue Stop
stopped!
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
end
end
|