Sha256: 4a4265e49a1f3cdc0dd7f31d531a7bd5e5df92ae87afbd24d93381fda3df03b2

Contents?: true

Size: 1.58 KB

Versions: 6

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

require "timeout"

module HTTPX
  class Timeout
    LOOP_TIMEOUT = 5

    def self.new(opts = {})
      return opts if opts.is_a?(Timeout)
      super
    end

    def initialize(loop_timeout: 5, total_timeout: nil)
      @loop_timeout = loop_timeout
      @total_timeout = total_timeout
      reset_counter
    end

    def timeout
      @loop_timeout || @total_timeout
    ensure
      log_time
    end

    def ==(other)
      if other.is_a?(Timeout)
        @loop_timeout == other.instance_variable_get(:@loop_timeout) &&
          @total_timeout == other.instance_variable_get(:@total_timeout)
      else
        super
      end
    end

    def merge(other)
      case other
      when Hash
        timeout = Timeout.new(other)
        merge(timeout)
      when Timeout
        loop_timeout = other.instance_variable_get(:@loop_timeout) || @loop_timeout
        total_timeout = other.instance_variable_get(:@total_timeout) || @total_timeout
        Timeout.new(loop_timeout: loop_timeout, total_timeout: total_timeout)
      else
        raise ArgumentError, "can't merge with #{other.class}"
      end
    end

    private

    def reset_counter
      @time_left = @total_timeout
    end

    def reset_timer
      @started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    end

    def log_time
      return unless @time_left
      return reset_timer unless @started
      @time_left -= (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @started)
      raise TimeoutError, "Timed out after #{@total_timeout} seconds" if @time_left <= 0

      reset_timer
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
httpx-0.1.0 lib/httpx/timeout.rb
httpx-0.0.5 lib/httpx/timeout.rb
httpx-0.0.4 lib/httpx/timeout.rb
httpx-0.0.3 lib/httpx/timeout.rb
httpx-0.0.2 lib/httpx/timeout.rb
httpx-0.0.1 lib/httpx/timeout.rb