fleet 0.1.3 → 0.1.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. data/lib/fleet.rb +51 -7
  2. metadata +1 -1
data/lib/fleet.rb CHANGED
@@ -1,29 +1,73 @@
1
1
  require "socket"
2
2
  require "yajl"
3
+ require "system_timer"
4
+
3
5
 
4
6
  class Fleet
5
7
  def initialize(options = {})
6
- @host = options[:host] || "127.0.0.1"
7
- @port = options[:port] || 3400
8
- @socket = TCPSocket.new(@host, @port)
8
+ @host = options[:host] || "127.0.0.1"
9
+ @port = options[:port] || 3400
10
+ @timeout = options[:timeout] || 5
11
+ @password = options[:password]
9
12
  @json_encoder = Yajl::Encoder
10
13
  @json_parser = Yajl::Parser
14
+ connect
11
15
  end
12
16
 
13
17
  def query(q)
14
18
  request = @json_encoder.encode(q)
15
- @socket.write(request)
16
- @socket.write("\r\n")
17
- response = @socket.gets
19
+ response = write_and_read_with_retry(request)
18
20
  status, value = @json_parser.parse(response)
19
21
  status == 0 ? value : raise(value)
20
22
  end
21
23
 
22
24
  def close
23
- @socket.close
25
+ disconnect
24
26
  end
25
27
 
26
28
  def to_s
27
29
  "FleetDB client connected to #{@host}:#{@port}"
28
30
  end
31
+
32
+ private
33
+
34
+ def connect
35
+ @socket =
36
+ with_timeout do
37
+ socket = TCPSocket.new(@host, @port)
38
+ socket.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1
39
+ socket
40
+ end
41
+ end
42
+
43
+ def disconnect
44
+ @socket.close rescue nil
45
+ @socket = nil
46
+ end
47
+
48
+ def write_and_read_with_retry(request)
49
+ begin
50
+ write_and_read(request)
51
+ rescue Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Timeout::Error
52
+ disconnect
53
+ connect
54
+ write_and_read(request)
55
+ end
56
+ end
57
+
58
+ def write_and_read(request)
59
+ with_timeout do
60
+ @socket.write(request)
61
+ @socket.write("\r\n")
62
+ @socket.gets
63
+ end
64
+ end
65
+
66
+ def with_timeout
67
+ if @timeout == 0
68
+ yield
69
+ else
70
+ SystemTimer.timeout_after(@timeout) { yield }
71
+ end
72
+ end
29
73
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fleet
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.3
4
+ version: 0.1.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mark McGranaghan