Class: Rpush::Daemon::TcpConnection

Inherits:
Object
  • Object
show all
Includes:
Loggable, Reflectable
Defined in:
lib/rpush/daemon/tcp_connection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#log_error, #log_info, #log_warn

Methods included from Reflectable

#reflect

Constructor Details

#initialize(app, host, port) ⇒ TcpConnection

Returns a new instance of TcpConnection.



15
16
17
18
19
20
21
22
# File 'lib/rpush/daemon/tcp_connection.rb', line 15

def initialize(app, host, port)
  @app = app
  @host = host
  @port = port
  @certificate = app.certificate
  @password = app.password
  written
end

Instance Attribute Details

#last_writeObject

Returns the value of attribute last_write.



9
10
11
# File 'lib/rpush/daemon/tcp_connection.rb', line 9

def last_write
  @last_write
end

Class Method Details

.idle_periodObject



11
12
13
# File 'lib/rpush/daemon/tcp_connection.rb', line 11

def self.idle_period
  30.minutes
end

Instance Method Details

#closeObject



29
30
31
32
33
# File 'lib/rpush/daemon/tcp_connection.rb', line 29

def close
  @ssl_socket.close if @ssl_socket
  @tcp_socket.close if @tcp_socket
rescue IOError # rubocop:disable HandleExceptions
end

#connectObject



24
25
26
27
# File 'lib/rpush/daemon/tcp_connection.rb', line 24

def connect
  @ssl_context = setup_ssl_context
  @tcp_socket, @ssl_socket = connect_socket
end

#read(num_bytes) ⇒ Object



35
36
37
# File 'lib/rpush/daemon/tcp_connection.rb', line 35

def read(num_bytes)
  @ssl_socket.read(num_bytes)
end

#reconnectObject



68
69
70
71
# File 'lib/rpush/daemon/tcp_connection.rb', line 68

def reconnect
  close
  @tcp_socket, @ssl_socket = connect_socket
end

#select(timeout) ⇒ Object



39
40
41
# File 'lib/rpush/daemon/tcp_connection.rb', line 39

def select(timeout)
  IO.select([@ssl_socket], nil, nil, timeout)
end

#write(data) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rpush/daemon/tcp_connection.rb', line 43

def write(data)
  reconnect_idle if idle_period_exceeded?

  retry_count = 0

  begin
    write_data(data)
  rescue Errno::EPIPE, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError, IOError => e
    retry_count += 1

    if retry_count == 1
      log_error("Lost connection to #{@host}:#{@port} (#{e.class.name}), reconnecting...")
      reflect(:tcp_connection_lost, @app, e)
    end

    if retry_count <= 3
      reconnect
      sleep 1
      retry
    else
      raise TcpConnectionError, "#{@app.name} tried #{retry_count - 1} times to reconnect but failed (#{e.class.name})."
    end
  end
end