Class: Async::Scheduler

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

Overview

Handles scheduling of fibers. Implements the fiber scheduler interface.

Direct Known Subclasses

Reactor

Defined Under Namespace

Classes: ClosedError, FiberInterrupt

Constant Summary collapse

WORKER_POOL =
ENV.fetch("ASYNC_SCHEDULER_WORKER_POOL", nil).then do |value|
  value == "true" ? true : nil
end
WorkerPool =
nil

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

Instance Method Summary collapse

Methods inherited from Node

#The parent node.=, #annotate, #backtrace, #cancelled?, #children?, #consume, #description, #finished?, #print_hierarchy, #root, #stopped?, #transient=, #transient?, #traverse, #wait

Constructor Details

#initialize(parent = nil, selector: nil, profiler: Profiler&.default, worker_pool: WORKER_POOL) ⇒ Scheduler

Create a new scheduler.



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

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(BlockingOperationWait)
  end
end

Class Method Details

.supported?Boolean

Whether the fiber scheduler is supported.

Returns:

  • (Boolean)


47
48
49
# File 'lib/async/scheduler.rb', line 47

def self.supported?
  true
end

Instance Method Details

#address_resolve(hostname) ⇒ Object

Resolve the address of the given hostname.



295
296
297
298
299
300
# File 'lib/async/scheduler.rb', line 295

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

#async(*arguments, **options, &block) ⇒ Object

Deprecated.

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.



633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/async/scheduler.rb', line 633

def async(*arguments, **options, &block)
  # Since this method is called by `run`, this warning is too excessive:
  # warn("Async::Scheduler#async is deprecated. Use `run` or `Task#async` instead.", uplevel: 1, category: :deprecated) if $VERBOSE
  
  Kernel.raise ClosedError if @selector.nil?
  
  task = Task.new(Task.current? || self, **options, &block)
  
  task.run(*arguments)
  
  return task
end

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



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/async/scheduler.rb', line 234

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

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

Cancel all children, including transient children.



534
535
536
537
538
539
540
541
542
# File 'lib/async/scheduler.rb', line 534

def cancel(later = false, cause: $!)
  if @children and !cause
    cause = Cancel::Cause.for("Cancelling task!")
  end
  
  @children&.each do |child|
    child.cancel(later, cause: cause)
  end
end

#closeObject

Terminate all child tasks and close the scheduler.



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/async/scheduler.rb', line 150

def close
  unless @children.nil?
    self.run_loop do
      until self.terminate
        self.run_once!
      end
    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.
  if selector = @selector
    @selector = nil
    selector.close
  end
  
  if worker_pool = @worker_pool
    @worker_pool = nil
    worker_pool.close
  end
  
  consume
end

#closed?Boolean

Returns:

  • (Boolean)


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

def closed?
  @selector.nil?
end

#fiberObject

Create a new fiber and return it without starting execution.



648
649
650
# File 'lib/async/scheduler.rb', line 648

def fiber(...)
  return async(...).fiber
end

#fiber_interrupt(fiber, exception) ⇒ Object

Raise an exception on the specified fiber, waking up the event loop if necessary.



412
413
414
415
# File 'lib/async/scheduler.rb', line 412

def fiber_interrupt(fiber, exception)
  # Fiber.blocking{$stderr.puts "fiber_interrupt(#{fiber}, #{exception})"}
  unblock(nil, FiberInterrupt.new(fiber, exception))
end

#interruptObject

Interrupt the event loop and cause it to exit.



188
189
190
191
# File 'lib/async/scheduler.rb', line 188

def interrupt
  @interrupted = true
  @selector&.wakeup
end

#io_read(io, buffer, offset, length) ⇒ Object

Read at most the specified number of bytes from the IO into the buffer.



349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/async/scheduler.rb', line 349

def io_read(io, buffer, offset, length)
  fiber = Fiber.current
  
  if timeout = io.timeout
    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, offset, length)
ensure
  timer&.cancel!
end

#io_selectObject

Wait for the specified IOs to become ready for the specified events.



441
442
443
444
445
446
447
448
# File 'lib/async/scheduler.rb', line 441

def io_select(...)
  Thread.new do
    # Don't make unnecessary output, since we will propagate the exception:
    Thread.current.report_on_exception = false
    
    ::IO.select(...)
  end.value
end

#io_wait(io, events, timeout = nil) ⇒ Object

Wait for the specified IO to become ready for the specified events.



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

def io_wait(io, events, timeout = nil)
  fiber = Fiber.current
  expired = false
  
  if timeout
    # If an explicit timeout is specified, we expect that the user will handle it themselves:
    timer = @timers.after(timeout) do
      expired = true
      fiber.transfer
    end
  elsif timeout = io.timeout
    # 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
  
  # A selector wait may return a falsy result when the fiber is resumed without the requested IO becoming ready. For example, a deferred unblock from a previous blocking operation may arrive after the fiber has moved on to this wait. Retry these stale or spurious wake-ups without resetting the original timer.
  until result = @selector.io_wait(fiber, io, events)
    # If the original timer resumed the fiber, the false result represents the timeout rather than a spurious wake-up:
    return false if expired
  end
  
  return result
ensure
  timer&.cancel!
end

#io_write(io, buffer, offset, length) ⇒ Object

Write at most the specified number of bytes from the buffer to the IO.



373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/async/scheduler.rb', line 373

def io_write(io, buffer, offset, length)
  fiber = Fiber.current
  
  if timeout = io.timeout
    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, offset, length)
ensure
  timer&.cancel!
end

#kernel_sleep(duration = nil) ⇒ Object

Sleep for the specified duration.



279
280
281
282
283
284
285
286
287
# File 'lib/async/scheduler.rb', line 279

def kernel_sleep(duration = nil)
  # Fiber.blocking{$stderr.puts "kernel_sleep(#{duration}, #{Fiber.current})"}
  
  if duration
    self.block(nil, duration)
  else
    self.transfer
  end
end

#loadObject

Compute the scheduler load according to the busy and idle times that are updated by the run loop.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/async/scheduler.rb', line 107

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

#process_forkObject

Handle fork in the child process. This method is called automatically when Process.fork is invoked on Ruby versions < 4 and cleans up the scheduler state. On Ruby 4+, the scheduler is automatically cleaned up by the Ruby runtime.

The child process starts with a clean slate - no scheduler is set. Users can create a new scheduler if needed.



699
700
701
702
703
704
705
706
707
708
# File 'lib/async/scheduler.rb', line 699

def process_fork
  @profiler = nil
  @children = nil
  @selector = nil
  @timers = nil
  @blocked = 0
  
  # Close the scheduler:
  Fiber.set_scheduler(nil)
end

#process_wait(pid, flags) ⇒ Object

Wait for the specified process ID to exit.



426
427
428
429
430
431
432
433
434
435
# File 'lib/async/scheduler.rb', line 426

def process_wait(pid, flags)
  fiber = Fiber.current
  
  # A native process wait may be interrupted before the child exits. io-event reports this as `false` and leaves the retry policy to the scheduler. Retry only `false`, since `nil` is a legitimate result for `Process::WNOHANG`.
  while true
    status = @selector.process_wait(fiber, pid, flags)
    
    return status unless status == false
  end
end

#push(fiber) ⇒ Object

Schedule a fiber (or equivalent object) to be resumed on the next loop through the reactor.



205
206
207
# File 'lib/async/scheduler.rb', line 205

def push(fiber)
  @selector.push(fiber)
end

#raiseObject

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.



215
216
217
# File 'lib/async/scheduler.rb', line 215

def raise(...)
  @selector.raise(...)
end

#resume(fiber, *arguments) ⇒ Object

Resume execution of the specified fiber.



223
224
225
# File 'lib/async/scheduler.rb', line 223

def resume(fiber, *arguments)
  @selector.resume(fiber, *arguments)
end

#runObject

Run the reactor until all tasks are finished. Proxies arguments to #async immediately before entering the loop, if a block is provided.

Forwards all parameters to #async if a block is given.



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/async/scheduler.rb', line 601

def run(...)
  Kernel.raise ClosedError if @selector.nil?
  
  begin
    @profiler&.start
    
    initial_task = nil
    
    if block_given?
      initial = proc do
        initial_task = self.async(...)
      end
    end
    
    self.run_loop(initial) do
      run_once
    end
    
    return initial_task
  ensure
    @profiler&.stop
  end
end

#run_once(timeout = nil) ⇒ Object

Run one iteration of the event loop.



500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/async/scheduler.rb', line 500

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

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



129
130
131
132
133
134
135
136
# File 'lib/async/scheduler.rb', line 129

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

#stopObject

Backward compatibility alias for cancel.



545
546
547
# File 'lib/async/scheduler.rb', line 545

def stop(...)
  cancel(...)
end

#terminateObject

Terminate all child tasks.



139
140
141
142
143
144
145
146
# File 'lib/async/scheduler.rb', line 139

def terminate
  # If that doesn't work, take more serious action:
  @children&.each do |child|
    child.terminate
  end
  
  return @children.nil?
end

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



688
689
690
691
692
# File 'lib/async/scheduler.rb', line 688

def timeout_after(duration, exception, message, &block)
  with_timeout(duration, exception, message) do
    yield duration
  end
end

#to_sObject



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

def to_s
  "\#<#{self.description} #{@children&.size || 0} children (#{cancelled? ? 'cancelled' : 'running'})>"
end

#transferObject

Transfer from the calling fiber to the event loop.



194
195
196
# File 'lib/async/scheduler.rb', line 194

def transfer
  @selector.transfer
end

#unblock(blocker, fiber) ⇒ Object

Unblock a fiber that was previously blocked.



263
264
265
266
267
268
269
270
271
# File 'lib/async/scheduler.rb', line 263

def unblock(blocker, fiber)
  # Fiber.blocking{$stderr.puts "unblock(#{blocker}, #{fiber})"}
  
  # This operation is protected by the GVL:
  if selector = @selector
    selector.push(fiber)
    selector.wakeup
  end
end

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



661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/async/scheduler.rb', line 661

def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
  fiber = Fiber.current
  
  timer = @timers.after(duration) do
    if fiber.alive?
      fiber.raise(exception, message)
    end
  end
  
  if block.arity.zero?
    yield
  else
    yield Timeout.new(@timers, timer)
  end
ensure
  timer&.cancel!
end

#yieldObject

Yield the current fiber and resume it on the next iteration of the event loop.



199
200
201
# File 'lib/async/scheduler.rb', line 199

def yield
  @selector.yield
end