Sha256: 3b44c6f90a85582a20ad583489960c96524f5b14dad0a3327a8fa03ca9990479

Contents?: true

Size: 930 Bytes

Versions: 2

Compression:

Stored size: 930 Bytes

Contents

# frozen_string_literal: true

# idea taken from the example given in trio:
# https://www.youtube.com/watch?v=oLkfnc_UMcE

require 'bundler/setup'
require 'polyphony/http'

async def try_connect(target, supervisor)
  puts "trying #{target[2]}"
  socket = Polyphony::Net.tcp_connect(target[2], 80)
  supervisor.stop!([target[2], socket])
rescue IOError, SystemCallError
end

def happy_eyeballs(hostname, port, max_wait_time: 0.025)
  targets = Socket.getaddrinfo(hostname, port, :INET, :STREAM)
  t0 = Time.now
  cancel_after(5) do
    success = supervise do |supervisor|
      targets.each_with_index do |t, idx|
        sleep(max_wait_time) if idx > 0
        supervisor.coproc try_connect(t, supervisor)
      end
    end
    if success
      puts "success: %s (%.3fs)" % [success[0], Time.now - t0]
    else
      puts "timed out (#{Time.now - t0}s)"
    end
  end
end

# Let's try it out:
happy_eyeballs("debian.org", "https")

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polyphony-0.19 examples/http/happy_eyeballs.rb
polyphony-0.17 examples/http/happy_eyeballs.rb