Sha256: 8722884e22c883ea6856dfe739cbda22e0f19219705f7d6e40bb1a79c9c575aa

Contents?: true

Size: 1.39 KB

Versions: 27

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

require "socket"

module CoreExtensions
  module TCPSocketExt
    def self.prepended(base)
      base.prepend Initializer
    end

    module Initializer
      CONNECTION_TIMEOUT = 5
      IPV4_DELAY_SECONDS = 0.1

      def initialize(host, serv, *rest)
        mutex = Thread::Mutex.new
        addrs = []
        threads = []
        cond_var = Thread::ConditionVariable.new

        Addrinfo.foreach(host, serv, nil, :STREAM) do |addr|
          Thread.report_on_exception = false

          threads << Thread.new(addr) do
            # give head start to ipv6 addresses
            sleep IPV4_DELAY_SECONDS if addr.ipv4?

            # raises Errno::ECONNREFUSED when ip:port is unreachable
            Socket.tcp(addr.ip_address, serv, connect_timeout: CONNECTION_TIMEOUT).close
            mutex.synchronize do
              addrs << addr.ip_address
              cond_var.signal
            end
          end
        end

        mutex.synchronize do
          timeout_time = CONNECTION_TIMEOUT + Time.now.to_f
          while addrs.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0
            cond_var.wait(mutex, remaining_time)
          end

          host = addrs.shift unless addrs.empty?
        end

        threads.each {|t| t.kill.join if t.alive? }

        super(host, serv, *rest)
      end
    end
  end
end

TCPSocket.prepend CoreExtensions::TCPSocketExt

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
rubygems-update-3.6.3 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.6.2 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.6.1 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.6.0 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.23 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.22 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.21 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.20 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.19 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.18 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.17 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.16 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.15 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.14 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.13 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.12 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.10 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.9 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.8 lib/rubygems/core_ext/tcpsocket_init.rb
rubygems-update-3.5.7 lib/rubygems/core_ext/tcpsocket_init.rb