Class: Async::Scheduler
Overview
Handles scheduling of fibers. Implements the fiber scheduler interface.
Direct Known Subclasses
Defined Under Namespace
Classes: ClosedError
Constant Summary collapse
- WORKER_POOL =
ENV.fetch("ASYNC_SCHEDULER_WORKER_POOL", nil).then do |value| value == "true" ? true : nil end
Instance Attribute Summary
Attributes inherited from Node
#A useful identifier for the current node., #Optional list of children., #annotation, #children, #head, #parent, #tail
Class Method Summary collapse
-
.supported? ⇒ Boolean
Whether the fiber scheduler is supported.
Instance Method Summary collapse
-
#address_resolve(hostname) ⇒ Object
Resolve the address of the given hostname.
-
#async(*arguments, **options, &block) ⇒ Object
deprecated
Deprecated.
Use #run or Task#async instead.
-
#block(blocker, timeout) ⇒ Object
Invoked when a fiber tries to perform a blocking operation which cannot continue.
-
#close ⇒ Object
Terminate all child tasks and close the scheduler.
- #closed? ⇒ Boolean
- #fiber ⇒ Object
-
#initialize(parent = nil, selector: nil, profiler: Profiler&.default, worker_pool: WORKER_POOL) ⇒ Scheduler
constructor
Create a new scheduler.
-
#interrupt ⇒ Object
Interrupt the event loop and cause it to exit.
-
#io_read(io, buffer, length, offset = 0) ⇒ Object
Read from the specified IO into the buffer.
-
#io_wait(io, events, timeout = nil) ⇒ Object
Wait for the specified IO to become ready for the specified events.
-
#io_write(io, buffer, length, offset = 0) ⇒ Object
Write the specified buffer to the IO.
-
#kernel_sleep(duration = nil) ⇒ Object
Sleep for the specified duration.
-
#load ⇒ Object
Compute the scheduler load according to the busy and idle times that are updated by the run loop.
-
#process_wait(pid, flags) ⇒ Object
Wait for the specified process ID to exit.
-
#push(fiber) ⇒ Object
Schedule a fiber (or equivalent object) to be resumed on the next loop through the reactor.
-
#raise ⇒ Object
Raise an exception on a specified fiber with the given arguments.
-
#resume(fiber, *arguments) ⇒ Object
Resume execution of the specified fiber.
-
#run ⇒ Object
Run the reactor until all tasks are finished.
-
#run_once(timeout = nil) ⇒ Object
Run one iteration of the event loop.
-
#scheduler_close(error = $!) ⇒ Object
Invoked when the fiber scheduler is being closed.
-
#stop ⇒ Object
Stop all children, including transient children.
-
#terminate ⇒ Object
Terminate all child tasks.
-
#timeout_after(duration, exception, message, &block) ⇒ Object
Invoke the block, but after the specified timeout, raise the specified exception with the given message.
- #to_s ⇒ Object
-
#transfer ⇒ Object
Transfer from the calling fiber to the event loop.
-
#unblock(blocker, fiber) ⇒ Object
Unblock a fiber that was previously blocked.
-
#with_timeout(duration, exception = TimeoutError, message = "execution expired", &block) ⇒ Object
Invoke the block, but after the specified timeout, raise TimeoutError in any currenly blocking operation.
-
#yield ⇒ Object
Yield the current fiber and resume it on the next iteration of the event loop.
Methods inherited from Node
#The parent node.=, #annotate, #backtrace, #children?, #consume, #description, #finished?, #print_hierarchy, #root, #stopped?, #transient=, #transient?, #traverse
Constructor Details
permalink #initialize(parent = nil, selector: nil, profiler: Profiler&.default, worker_pool: WORKER_POOL) ⇒ Scheduler
Create a new scheduler.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/async/scheduler.rb', line 53 def initialize(parent = nil, selector: nil, profiler: Profiler&.default, worker_pool: WORKER_POOL) super(parent) @selector = selector || ::IO::Event::Selector.new(Fiber.current) @profiler = profiler @interrupted = false @blocked = 0 @busy_time = 0.0 @idle_time = 0.0 @timers = ::IO::Event::Timers.new if worker_pool == true @worker_pool = WorkerPool.new else @worker_pool = worker_pool end if @worker_pool self.singleton_class.prepend(WorkerPool::BlockingOperationWait) end end |
Class Method Details
permalink .supported? ⇒ Boolean
Whether the fiber scheduler is supported.
44 45 46 |
# File 'lib/async/scheduler.rb', line 44 def self.supported? true end |
Instance Method Details
permalink #address_resolve(hostname) ⇒ Object
Resolve the address of the given hostname.
265 266 267 268 269 270 |
# File 'lib/async/scheduler.rb', line 265 def address_resolve(hostname) # On some platforms, hostnames may contain a device-specific suffix (e.g. %en0). We need to strip this before resolving. # See <https://github.com/socketry/async/issues/180> for more details. hostname = hostname.split("%", 2).first ::Resolv.getaddresses(hostname) end |
permalink #async(*arguments, **options, &block) ⇒ Object
Use #run or Task#async instead.
Start an asynchronous task within the specified reactor. The task will be executed until the first blocking call, at which point it will yield and and this method will return.
528 529 530 531 532 533 534 535 536 537 538 |
# File 'lib/async/scheduler.rb', line 528 def async(*arguments, **, &block) # warn "Async::Scheduler#async is deprecated. Use `run` or `Task#async` instead.", uplevel: 1, category: :deprecated Kernel.raise ClosedError if @selector.nil? task = Task.new(Task.current? || self, **, &block) task.run(*arguments) return task end |
permalink #block(blocker, timeout) ⇒ Object
Invoked when a fiber tries to perform a blocking operation which cannot continue. A corresponding call #unblock must be performed to allow this fiber to continue.
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/async/scheduler.rb', line 206 def block(blocker, timeout) # $stderr.puts "block(#{blocker}, #{Fiber.current}, #{timeout})" fiber = Fiber.current if timeout timer = @timers.after(timeout) do if fiber.alive? fiber.transfer(false) end end end begin @blocked += 1 @selector.transfer ensure @blocked -= 1 end ensure timer&.cancel! end |
permalink #close ⇒ Object
Terminate all child tasks and close the scheduler.
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/async/scheduler.rb', line 124 def close self.run_loop do until self.terminate self.run_once! end end Kernel.raise "Closing scheduler with blocked operations!" if @blocked > 0 ensure # We want `@selector = nil` to be a visible side effect from this point forward, specifically in `#interrupt` and `#unblock`. If the selector is closed, then we don't want to push any fibers to it. selector = @selector @selector = nil selector&.close worker_pool = @worker_pool @worker_pool = nil worker_pool&.close consume end |
permalink #closed? ⇒ Boolean
149 150 151 |
# File 'lib/async/scheduler.rb', line 149 def closed? @selector.nil? end |
permalink #fiber ⇒ Object
[View source]
540 541 542 |
# File 'lib/async/scheduler.rb', line 540 def fiber(...) return async(...).fiber end |
permalink #interrupt ⇒ Object
Interrupt the event loop and cause it to exit.
160 161 162 163 |
# File 'lib/async/scheduler.rb', line 160 def interrupt @interrupted = true @selector&.wakeup end |
permalink #io_read(io, buffer, length, offset = 0) ⇒ Object
Read from the specified IO into the buffer.
320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/async/scheduler.rb', line 320 def io_read(io, buffer, length, offset = 0) fiber = Fiber.current if timeout = get_timeout(io) timer = @timers.after(timeout) do fiber.raise(::IO::TimeoutError, "Timeout (#{timeout}s) while waiting for IO to become readable!") end end @selector.io_read(fiber, io, buffer, length, offset) ensure timer&.cancel! end |
permalink #io_wait(io, events, timeout = nil) ⇒ Object
Wait for the specified IO to become ready for the specified events.
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/async/scheduler.rb', line 290 def io_wait(io, events, timeout = nil) fiber = Fiber.current if timeout # If an explicit timeout is specified, we expect that the user will handle it themselves: timer = @timers.after(timeout) do fiber.transfer end elsif timeout = get_timeout(io) # Otherwise, if we default to the io's timeout, we raise an exception: timer = @timers.after(timeout) do fiber.raise(::IO::TimeoutError, "Timeout (#{timeout}s) while waiting for IO to become ready!") end end return @selector.io_wait(fiber, io, events) ensure timer&.cancel! end |
permalink #io_write(io, buffer, length, offset = 0) ⇒ Object
Write the specified buffer to the IO.
344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/async/scheduler.rb', line 344 def io_write(io, buffer, length, offset = 0) fiber = Fiber.current if timeout = get_timeout(io) timer = @timers.after(timeout) do fiber.raise(::IO::TimeoutError, "Timeout (#{timeout}s) while waiting for IO to become writable!") end end @selector.io_write(fiber, io, buffer, length, offset) ensure timer&.cancel! end |
permalink #kernel_sleep(duration = nil) ⇒ Object
Sleep for the specified duration.
251 252 253 254 255 256 257 |
# File 'lib/async/scheduler.rb', line 251 def kernel_sleep(duration = nil) if duration self.block(nil, duration) else self.transfer end end |
permalink #load ⇒ Object
Compute the scheduler load according to the busy and idle times that are updated by the run loop.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/async/scheduler.rb', line 81 def load total_time = @busy_time + @idle_time # If the total time is zero, then the load is zero: return 0.0 if total_time.zero? # We normalize to a 1 second window: if total_time > 1.0 ratio = 1.0 / total_time @busy_time *= ratio @idle_time *= ratio # We don't need to divide here as we've already normalised it to a 1s window: return @busy_time else return @busy_time / total_time end end |
permalink #process_wait(pid, flags) ⇒ Object
Wait for the specified process ID to exit.
369 370 371 |
# File 'lib/async/scheduler.rb', line 369 def process_wait(pid, flags) return @selector.process_wait(Fiber.current, pid, flags) end |
permalink #push(fiber) ⇒ Object
Schedule a fiber (or equivalent object) to be resumed on the next loop through the reactor.
177 178 179 |
# File 'lib/async/scheduler.rb', line 177 def push(fiber) @selector.push(fiber) end |
permalink #raise ⇒ Object
Raise an exception on a specified fiber with the given arguments.
This internally schedules the current fiber to be ready, before raising the exception, so that it will later resume execution.
187 188 189 |
# File 'lib/async/scheduler.rb', line 187 def raise(...) @selector.raise(...) end |
permalink #resume(fiber, *arguments) ⇒ Object
Resume execution of the specified fiber.
195 196 197 |
# File 'lib/async/scheduler.rb', line 195 def resume(fiber, *arguments) @selector.resume(fiber, *arguments) end |
permalink #run ⇒ Object
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
# File 'lib/async/scheduler.rb', line 502 def run(...) Kernel.raise ClosedError if @selector.nil? begin @profiler&.start initial_task = self.async(...) if block_given? self.run_loop do run_once end return initial_task ensure @profiler&.stop end end |
permalink #run_once(timeout = nil) ⇒ Object
Run one iteration of the event loop.
423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
# File 'lib/async/scheduler.rb', line 423 def run_once(timeout = nil) Kernel.raise "Running scheduler on non-blocking fiber!" unless Fiber.blocking? if self.finished? self.stop end # If we are finished, we stop the task tree and exit: if @children.nil? return false end return run_once!(timeout) end |
permalink #scheduler_close(error = $!) ⇒ Object
Invoked when the fiber scheduler is being closed.
Executes the run loop until all tasks are finished, then closes the scheduler.
103 104 105 106 107 108 109 110 |
# File 'lib/async/scheduler.rb', line 103 def scheduler_close(error = $!) # If the execution context (thread) was handling an exception, we want to exit as quickly as possible: unless error self.run end ensure self.close end |
permalink #stop ⇒ Object
Stop all children, including transient children.
457 458 459 460 461 |
# File 'lib/async/scheduler.rb', line 457 def stop @children&.each do |child| child.stop end end |
permalink #terminate ⇒ Object
Terminate all child tasks.
113 114 115 116 117 118 119 120 |
# File 'lib/async/scheduler.rb', line 113 def terminate # If that doesn't work, take more serious action: @children&.each do |child| child.terminate end return @children.nil? end |
permalink #timeout_after(duration, exception, message, &block) ⇒ Object
Invoke the block, but after the specified timeout, raise the specified exception with the given message. If the block runs to completion before the timeout occurs or there are no non-blocking operations after the timeout expires, the code will complete without any exception.
576 577 578 579 580 |
# File 'lib/async/scheduler.rb', line 576 def timeout_after(duration, exception, , &block) with_timeout(duration, exception, ) do |timer| yield duration end end |
permalink #to_s ⇒ Object
[View source]
154 155 156 |
# File 'lib/async/scheduler.rb', line 154 def to_s "\#<#{self.description} #{@children&.size || 0} children (#{stopped? ? 'stopped' : 'running'})>" end |
permalink #transfer ⇒ Object
Transfer from the calling fiber to the event loop.
166 167 168 |
# File 'lib/async/scheduler.rb', line 166 def transfer @selector.transfer end |
permalink #unblock(blocker, fiber) ⇒ Object
Unblock a fiber that was previously blocked.
235 236 237 238 239 240 241 242 243 |
# File 'lib/async/scheduler.rb', line 235 def unblock(blocker, fiber) # $stderr.puts "unblock(#{blocker}, #{fiber})" # This operation is protected by the GVL: if selector = @selector selector.push(fiber) selector.wakeup end end |
permalink #with_timeout(duration, exception = TimeoutError, message = "execution expired", &block) ⇒ Object
Invoke the block, but after the specified timeout, raise TimeoutError in any currenly blocking operation. If the block runs to completion before the timeout occurs or there are no non-blocking operations after the timeout expires, the code will complete without any exception.
553 554 555 556 557 558 559 560 561 562 563 564 565 |
# File 'lib/async/scheduler.rb', line 553 def with_timeout(duration, exception = TimeoutError, = "execution expired", &block) fiber = Fiber.current timer = @timers.after(duration) do if fiber.alive? fiber.raise(exception, ) end end yield timer ensure timer&.cancel! end |
permalink #yield ⇒ Object
Yield the current fiber and resume it on the next iteration of the event loop.
171 172 173 |
# File 'lib/async/scheduler.rb', line 171 def yield @selector.yield end |