net_tcp_client 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e8ada0256a62a84b52bd1084e1c82d4735c28fafb652e933afb7828d9176a262
4
- data.tar.gz: ebb5a4e0ae53dffdc317b88263ed60a027b85cac35f1fa909fb626fad62fef88
3
+ metadata.gz: c8ff3b14fc47e63f2d733bd63abeda2177187bcefc8af9b8cc550ea456675897
4
+ data.tar.gz: f1ff58592eca02a9559fcb90a24c956bf3d8788550f4cb437ec9713473259727
5
5
  SHA512:
6
- metadata.gz: 74165666c671d74fd1ffe989692cf8f108145cdcf2f70cd82fc4f90730129e391deb8055177ea9eebabcd9d03ea6bdcbf60f117c8aa5f1fe77645a2762b46905
7
- data.tar.gz: b5de49d7560b9ed8a20fde3d211178b37481b5e988c7027afe2c87569f3d81c012aa8d5c4d79590ec5f47d2cfce41280e76cdf3c8cd4bad31d2f7fd2f48f077e
6
+ metadata.gz: 978ce566c440d8622b204fa9d171a02e65f320c6e81bd5db28b6a8445cc80e1ad3127a454163737ead74db939120f94feb007941f54cf0895c4e6385d3b41694
7
+ data.tar.gz: 4243b4d6ea2e9344c0c5f1ed1b622d54b8ee73bae0f0b5d754b8455b677fc945ddf1649f61361eaf818d71573c8278587f0eba2a3ec6ffaae895b3d059f92c89
data/README.md CHANGED
@@ -22,6 +22,7 @@ prevent a network issue from "hanging" the client program.
22
22
  * Read Timeout.
23
23
  * Write Timeout.
24
24
  * Fails over / load balances across all servers under a single DNS entry.
25
+ * IPv4 and IPv6.
25
26
  * Logging.
26
27
  * Optional trace level logging of all data sent or received.
27
28
  * Uses non blocking timeouts, instead of using threads such as used by the Timeout class.
@@ -62,6 +63,15 @@ if the connection is lost the next server is tried immediately.
62
63
  Net::TCPClient detects DNS entries that have multiple IP Addresses associated with them and
63
64
  adds each of the ip addresses for the single DNS name to the list of servers to try to connect to.
64
65
 
66
+ Both IPv4 and IPv6 addresses are used. A DNS name's IPv4 addresses are tried before its IPv6 addresses.
67
+ An IPv6 address in a server name must be enclosed in square brackets:
68
+
69
+ ~~~ruby
70
+ Net::TCPClient.connect(server: '[2001:db8::1]:3300') do |client|
71
+ client.write('Update the database')
72
+ end
73
+ ~~~
74
+
65
75
  If a server is unavailable, cannot connect, or the connection is lost, the next server is immediately
66
76
  tried. Once all servers have been exhausted, it will keep trying to connect, starting with the
67
77
  first server again.
@@ -6,14 +6,15 @@ module Net
6
6
  class Address
7
7
  attr_accessor :host_name, :ip_address, :port
8
8
 
9
- # Returns [Array<String>] ip addresses for the supplied DNS entry
10
- # Returns dns_name if it is already an IP Address
9
+ # Returns [Array<String>] the IPv4 and IPv6 addresses for the supplied DNS entry.
10
+ # Returns dns_name if it is already an IP Address.
11
+ #
12
+ # IPv4 addresses are listed before IPv6 addresses, each in the order the resolver returns them,
13
+ # so a host that has both still connects over IPv4 first, as it always has.
11
14
  def self.ip_addresses(dns_name)
12
- ips = []
13
- Socket.getaddrinfo(dns_name, nil, Socket::AF_INET, Socket::SOCK_STREAM).each do |s|
14
- ips << s[3] if s[0] == "AF_INET"
15
- end
16
- ips.uniq
15
+ infos = Addrinfo.getaddrinfo(dns_name, nil, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
16
+ ipv4, ipv6 = infos.select { |info| info.ipv4? || info.ipv6? }.partition(&:ipv4?)
17
+ (ipv4 + ipv6).map(&:ip_address).uniq
17
18
  end
18
19
 
19
20
  # Returns [Array<Net::TCPClient::Address>] addresses for a given DNS / host name.
@@ -28,31 +29,60 @@ module Net
28
29
  # Returns [Array<Net::TCPClient::Address>] addresses for a list of DNS / host name's
29
30
  # that are paired with their numbers
30
31
  #
31
- # server_name should be either a host_name, or ip address combined with a port:
32
+ # server_name should be either a host_name, or ip address combined with a port.
33
+ # An IPv6 address must be enclosed in square brackets:
32
34
  # "host_name:1234"
33
35
  # "192.168.1.10:80"
36
+ # "[2001:db8::1]:80"
34
37
  def self.addresses_for_server_name(server_name)
35
- dns_name, port = server_name.split(":")
36
- port = port.to_i
38
+ dns_name, port = parse_server_name(server_name)
37
39
  unless dns_name && port&.positive?
38
40
  raise(
39
41
  ArgumentError,
40
- "Invalid host_name: #{server_name.inspect}. Must be formatted as 'host_name:1234' or '192.168.1.10:80'"
42
+ "Invalid host_name: #{server_name.inspect}. " \
43
+ "Must be formatted as 'host_name:1234', '192.168.1.10:80' or '[2001:db8::1]:80'"
41
44
  )
42
45
  end
43
46
 
44
47
  addresses(dns_name, port)
45
48
  end
46
49
 
50
+ # Returns [String, Integer] the host name and port in the supplied server name,
51
+ # or nil for either one it does not have.
52
+ def self.parse_server_name(server_name)
53
+ match = server_name.to_s.match(/\A(?:\[(?<ipv6>[^\]]+)\]|(?<host>[^:\[\]]+)):(?<port>\d+)\z/)
54
+ return unless match
55
+
56
+ [match[:ipv6] || match[:host], match[:port].to_i]
57
+ end
58
+ private_class_method :parse_server_name
59
+
47
60
  def initialize(host_name, ip_address, port)
48
61
  @host_name = host_name
49
62
  @ip_address = ip_address
50
63
  @port = port.to_i
51
64
  end
52
65
 
66
+ # Returns [Integer] the address family of this address: Socket::AF_INET or Socket::AF_INET6
67
+ def family
68
+ addrinfo.afamily
69
+ end
70
+
71
+ # Returns [String] the packed socket address to connect to
72
+ def sockaddr
73
+ addrinfo.to_sockaddr
74
+ end
75
+
53
76
  def to_s
54
77
  "#{host_name}[#{ip_address}]:#{port}"
55
78
  end
79
+
80
+ private
81
+
82
+ # The ip address is numeric, so this does not look up DNS.
83
+ def addrinfo
84
+ Addrinfo.tcp(ip_address, port)
85
+ end
56
86
  end
57
87
  end
58
88
  end
@@ -39,7 +39,7 @@ module Net
39
39
 
40
40
  attr_accessor :connect_timeout, :read_timeout, :write_timeout,
41
41
  :connect_retry_count, :connect_retry_interval, :retry_count,
42
- :policy, :close_on_error, :buffered, :ssl, :proxy_server, :keepalive
42
+ :policy, :close_on_error, :buffered, :ssl, :keepalive
43
43
  attr_reader :servers, :address, :socket, :ssl_handshake_timeout
44
44
 
45
45
  # Supports embedding user supplied data along with this connection
@@ -88,7 +88,7 @@ module Net
88
88
  # end
89
89
  #
90
90
  def self.connect(params = {})
91
- connection = new(params)
91
+ connection = new(**params)
92
92
  yield(connection)
93
93
  ensure
94
94
  connection&.close
@@ -101,6 +101,8 @@ module Net
101
101
  # URL of the server to connect to with port number
102
102
  # 'localhost:2000'
103
103
  # '192.168.1.10:80'
104
+ # '[2001:db8::1]:80' (An IPv6 address must be enclosed in square brackets)
105
+ # A host name is resolved to all of its IPv4 and IPv6 addresses, IPv4 first.
104
106
  #
105
107
  # :servers [Array of String]
106
108
  # Array of URL's of servers to connect to with port numbers
@@ -191,10 +193,8 @@ module Net
191
193
  # This includes a Read Timeout
192
194
  # Default: true
193
195
  #
194
- # :proxy_server [String]
195
- # The host name and port in the form of 'host_name:1234' to forward
196
- # socket connections though.
197
- # Default: nil ( none )
196
+ # :proxy_server
197
+ # Not supported: raises ArgumentError. Connecting through a SOCKS proxy never worked.
198
198
  #
199
199
  # SSL Options
200
200
  # :ssl [true|false|Hash]
@@ -258,9 +258,15 @@ module Net
258
258
  @retry_count = retry_count
259
259
  @connect_retry_interval = connect_retry_interval.to_f
260
260
  @on_connect = on_connect
261
- @proxy_server = proxy_server
262
261
  @policy = policy
263
262
  @close_on_error = close_on_error
263
+ if proxy_server
264
+ raise(
265
+ ArgumentError,
266
+ "proxy_server: is not supported. Net::TCPClient cannot connect through a SOCKS proxy. " \
267
+ "See https://github.com/reidmorrison/net_tcp_client/issues/7"
268
+ )
269
+ end
264
270
  if ssl
265
271
  @ssl = ssl == true ? {} : ssl
266
272
  @ssl_handshake_timeout = (@ssl.delete(:handshake_timeout) || @connect_timeout).to_f
@@ -317,9 +323,13 @@ module Net
317
323
  sleep(connect_retry_interval)
318
324
  retry
319
325
  else
320
- message = "#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{e.class}: #{e.message}"
321
- logger.benchmark_error(message, exception: e, duration: (Time.now - start_time)) if respond_to?(:logger)
322
- raise ConnectionFailure.new(message, address.to_s, cause)
326
+ if respond_to?(:logger)
327
+ message = "#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries"
328
+ # Not measure_error: it raises the exception it is given, which would make what #connect
329
+ # raises depend on the log level.
330
+ logger.error(message: message, exception: e, duration: (Time.now - start_time) * 1000)
331
+ end
332
+ raise e
323
333
  end
324
334
  end
325
335
  end
@@ -351,7 +361,7 @@ module Net
351
361
  payload = {timeout: timeout}
352
362
  # With trace level also log the sent data
353
363
  payload[:data] = data if logger.trace?
354
- logger.benchmark_debug("#write", payload: payload) do
364
+ logger.measure_debug("#write", payload: payload) do
355
365
  payload[:bytes] = socket_write(data, timeout)
356
366
  end
357
367
  else
@@ -401,7 +411,7 @@ module Net
401
411
  def read(length, buffer = nil, timeout = read_timeout)
402
412
  if respond_to?(:logger)
403
413
  payload = {bytes: length, timeout: timeout}
404
- logger.benchmark_debug("#read", payload: payload) do
414
+ logger.measure_debug("#read", payload: payload) do
405
415
  data = socket_read(length, buffer, timeout)
406
416
  # With trace level also log the received data
407
417
  payload[:data] = data if logger.trace?
@@ -496,7 +506,7 @@ module Net
496
506
  def flush
497
507
  return unless socket
498
508
 
499
- respond_to?(:logger) ? logger.benchmark_debug("#flush") { socket.flush } : socket.flush
509
+ respond_to?(:logger) ? logger.measure_debug("#flush") { socket.flush } : socket.flush
500
510
  end
501
511
 
502
512
  def closed?
@@ -522,17 +532,17 @@ module Net
522
532
  # I.e. About 8.3 micro seconds per call
523
533
  def alive?
524
534
  return false if socket.nil? || closed?
535
+ return true unless IO.select([socket], nil, nil, 0)
525
536
 
526
- if IO.select([socket], nil, nil, 0)
527
- begin
528
- !socket.eof?
529
- rescue StandardError
530
- false
531
- end
532
- else
533
- true
534
- end
535
- rescue IOError
537
+ # Something is waiting to be read: data, the end of the connection, or with SSL, records that
538
+ # carry no data, such as TLS 1.3 session tickets. socket.eof? would then block until the server
539
+ # sends data, so read a byte without blocking instead, and put it back for the next #read.
540
+ byte = socket.read_nonblock(1, exception: false)
541
+ return false if byte.nil?
542
+
543
+ socket.ungetc(byte) if byte.is_a?(String)
544
+ true
545
+ rescue StandardError
536
546
  false
537
547
  end
538
548
 
@@ -565,12 +575,7 @@ module Net
565
575
  # Connect to the server at the supplied address
566
576
  # Returns the socket connection
567
577
  def connect_to_address(address)
568
- socket =
569
- if proxy_server
570
- ::SOCKSSocket.new("#{address.ip_address}:#{address.port}", proxy_server)
571
- else
572
- ::Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
573
- end
578
+ socket = ::Socket.new(address.family, Socket::SOCK_STREAM, 0)
574
579
  unless buffered
575
580
  socket.sync = true
576
581
  socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
@@ -591,14 +596,21 @@ module Net
591
596
  # Raises Net::TCPClient::ConnectionTimeout when the connection timeout has been exceeded
592
597
  # Raises Net::TCPClient::ConnectionFailure
593
598
  def socket_connect(socket, address, timeout)
594
- socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address)
599
+ socket_address = address.sockaddr
595
600
 
596
601
  # Timeout of -1 means wait forever for a connection
597
602
  return socket.connect(socket_address) if timeout == -1
598
603
 
599
604
  deadline = Time.now.utc + timeout
600
605
  begin
601
- non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) }
606
+ if socket.connect_nonblock(socket_address, exception: false) == :wait_writable
607
+ raise NonBlockingTimeout unless IO.select(nil, [socket], nil, check_time_remaining(deadline))
608
+
609
+ # Once the socket is writable, SO_ERROR holds the outcome of the connect. Calling connect again
610
+ # instead is not portable: on some platforms it raises Errno::EISCONN after a refused connect.
611
+ error = socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR).int
612
+ raise SystemCallError.new("connect(2) for #{address}", error) unless error.zero?
613
+ end
602
614
  rescue Errno::EISCONN
603
615
  # Connection was successful.
604
616
  rescue NonBlockingTimeout
@@ -646,14 +658,11 @@ module Net
646
658
  if timeout.negative?
647
659
  buffer.nil? ? socket.read(length) : socket.read(length, buffer)
648
660
  else
649
- deadline = Time.now.utc + timeout
650
- non_blocking(socket, deadline) do
651
- buffer.nil? ? socket.read_nonblock(length) : socket.read_nonblock(length, buffer)
652
- end
661
+ socket_read_nonblock(length, buffer, Time.now.utc + timeout)
653
662
  end
654
663
 
655
664
  # EOF before all the data was returned
656
- if result.nil? || (result.length < length)
665
+ if result.nil? || (result.bytesize < length)
657
666
  logger.warn "#read server closed the connection before #{length} bytes were returned" if respond_to?(:logger)
658
667
  raise ConnectionFailure.new("Connection lost while reading data", address.to_s, EOFError.new("end of file reached"))
659
668
  end
@@ -667,6 +676,26 @@ module Net
667
676
  raise ConnectionFailure.new(message, address.to_s, e)
668
677
  end
669
678
 
679
+ # Returns [String] the next length bytes from the socket, or fewer when the connection
680
+ # is closed before they all arrive.
681
+ #
682
+ # Raises NonBlockingTimeout when they have not all arrived by the deadline. The bytes read
683
+ # until then are put back, so that the next #read returns them.
684
+ def socket_read_nonblock(length, buffer, deadline)
685
+ result = buffer ? buffer.clear.force_encoding(Encoding::BINARY) : String.new(encoding: Encoding::BINARY)
686
+ begin
687
+ non_blocking(socket, deadline) do
688
+ result << socket.read_nonblock(length - result.bytesize) while result.bytesize < length
689
+ end
690
+ rescue NonBlockingTimeout
691
+ socket.ungetc(result) unless result.empty?
692
+ raise
693
+ rescue EOFError
694
+ # Fewer than length bytes: #socket_read reports the lost connection.
695
+ end
696
+ result
697
+ end
698
+
670
699
  class NonBlockingTimeout < ::SocketError
671
700
  end
672
701
 
@@ -1,5 +1,5 @@
1
1
  module Net
2
2
  class TCPClient
3
- VERSION = "2.2.1".freeze
3
+ VERSION = "2.3.0".freeze
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,18 +1,16 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: net_tcp_client
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.1
4
+ version: 2.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Reid Morrison
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2023-03-25 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies: []
13
12
  description: Net::TCPClient implements resilience features that many developers wish
14
13
  was already included in the standard Ruby libraries.
15
- email:
16
14
  executables: []
17
15
  extensions: []
18
16
  extra_rdoc_files: []
@@ -35,7 +33,6 @@ licenses:
35
33
  - Apache-2.0
36
34
  metadata:
37
35
  rubygems_mfa_required: 'true'
38
- post_install_message:
39
36
  rdoc_options: []
40
37
  require_paths:
41
38
  - lib
@@ -50,8 +47,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
50
47
  - !ruby/object:Gem::Version
51
48
  version: '0'
52
49
  requirements: []
53
- rubygems_version: 3.3.7
54
- signing_key:
50
+ rubygems_version: 3.6.9
55
51
  specification_version: 4
56
52
  summary: Net::TCPClient is a TCP Socket Client with built-in timeouts, retries, and
57
53
  logging