Module: TunnelRb::Server::SocketHelpers

Defined in:
lib/tunnel_rb/server/socket_helpers.rb

Constant Summary collapse

TCP_KEEPALIVE_IDLE =
60
TCP_KEEPALIVE_INTERVAL =
30
TCP_KEEPALIVE_PROBES =
3

Class Method Summary collapse

Class Method Details

.enable_tcp_keepalive(socket) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tunnel_rb/server/socket_helpers.rb', line 14

def enable_tcp_keepalive(socket)
  # Operate on the raw fd so this works for both plain TCP and TLS
  # sockets (SSLSocket does not define setsockopt itself).
  io = socket.respond_to?(:to_io) ? socket.to_io : socket
  io.setsockopt(:SOCKET, :SO_KEEPALIVE, true)
  if defined?(Socket::TCP_KEEPIDLE)
    io.setsockopt(:TCP, :TCP_KEEPIDLE, TCP_KEEPALIVE_IDLE)
    io.setsockopt(:TCP, :TCP_KEEPINTVL, TCP_KEEPALIVE_INTERVAL)
    io.setsockopt(:TCP, :TCP_KEEPCNT, TCP_KEEPALIVE_PROBES)
  elsif defined?(Socket::TCP_KEEPALIVE)
    io.setsockopt(:TCP, :TCP_KEEPALIVE, TCP_KEEPALIVE_IDLE)
  end
rescue StandardError => e
  warn "TCP keepalive not configured: #{e.message}"
end

.enable_tcp_nodelay(socket) ⇒ Object

Disables Nagle’s algorithm so small writes (TLS handshake records, short HTTP responses) go out immediately instead of waiting to coalesce. On the short-lived data sockets this avoids ~40ms Nagle/delayed-ACK stalls.



33
34
35
36
37
38
# File 'lib/tunnel_rb/server/socket_helpers.rb', line 33

def enable_tcp_nodelay(socket)
  io = socket.respond_to?(:to_io) ? socket.to_io : socket
  io.setsockopt(:TCP, :TCP_NODELAY, true)
rescue StandardError => e
  warn "TCP_NODELAY not configured: #{e.message}"
end