Sha256: 437a156ebe3e5ff4410c468b8a3603d5158612fdb458ff950861046f3cb40731

Contents?: true

Size: 1.32 KB

Versions: 7

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

require 'fiber'

module Bolt
  class PlanFuture
    attr_reader :fiber, :id
    attr_accessor :value

    def initialize(fiber, id, name = nil)
      @fiber = fiber
      @id    = id
      @name  = name
      @value = nil
    end

    def name
      @name || @id
    end

    def to_s
      "Future '#{name}'"
    end

    def alive?
      fiber.alive?
    end

    def raise(exception)
      # Make sure the value gets set
      @value = exception
      # This was introduced in Ruby 2.7
      begin
        # Raise an exception to kill the Fiber. If the Fiber has not been
        # resumed yet, or is already terminated this will raise a FiberError.
        # We don't especially care about the FiberError, as long as the Fiber
        # doesn't report itself as alive.
        fiber.raise(exception)
      rescue FiberError
        # If the Fiber is still alive, resume it with a block to raise the
        # exception which will terminate it.
        if fiber.alive?
          fiber.resume { raise(exception) }
        end
      end
    end

    def resume
      if fiber.alive?
        @value = fiber.resume
      else
        @value
      end
    end

    def state
      if fiber.alive?
        "running"
      elsif value.is_a?(Exception)
        "error"
      else
        "done"
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
bolt-3.13.0 lib/bolt/plan_future.rb
bolt-3.12.0 lib/bolt/plan_future.rb
bolt-3.11.0 lib/bolt/plan_future.rb
bolt-3.10.0 lib/bolt/plan_future.rb
bolt-3.9.2 lib/bolt/plan_future.rb
bolt-3.9.1 lib/bolt/plan_future.rb
bolt-3.9.0 lib/bolt/plan_future.rb