Search code examples
rubytimeouthashicorp-vault

Is a retry necessary here in a timeout?


I have the following code:

task :wait_for_vault_ssl_up do
  Timeout::timeout(15) do
    begin
      TCPSocket.new('localhost', 8200).close
      puts "Vault ssl up and ready!"
      true
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError
      puts "Vault ssl not ready... retrying"
      retry
      false
    end
  end
  rescue Timeout::Error
    false
end

In this, i set a timeout of 15 seconds and try to connect to the localhost:8200 my question is, if its not up, i currently do a retry in the rescue. is that necessary or will it automatically continue trying to connect for 15 seconds?


Solution

  • The use of retry will retry the execution of the whole block being rescued. So in this case, retry will start execution over again at your call to TCPSocket.new. This will happen immediately after the exception is rescued and there will not be a delay.

    As Stefan has mentioned in the comments, you should use Kernel#sleep before calling retry. This will continue retrying until interrupted, so if you found yourself in a situation where the SSL connection will never be ready, the code will loop forever. You can either keep track of a retry count, or continue utilizing Timeout::timeout, using a longer timeout length, at which point the loop should give up entirely.

    I think the clearer and simpler solution would be to use a retry counter, and give up after a predefined number of retries.