This repository has been archived by the owner on Jan 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 108
/
client.rb
116 lines (90 loc) · 2.35 KB
/
client.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
require "socket"
require "warden/protocol"
require "warden/client/v1"
module Warden
class Client
class Error < StandardError; end
class ServerError < Error; end
attr_reader :path
def initialize(path)
@path = path
@v1mode = false
end
def connected?
!@sock.nil?
end
def connect
raise "already connected" if connected?
@sock = ::UNIXSocket.new(path)
end
def disconnect
raise "not connected" unless connected?
@sock.close rescue nil
@sock = nil
end
def reconnect
disconnect if connected?
connect
end
def io
rv = yield
if rv.nil?
disconnect
raise ::EOFError
end
rv
end
def read
length = io { @sock.gets }
data = io { @sock.read(length.to_i) }
# Discard \r\n
io { @sock.read(2) }
wrapped_response = Warden::Protocol::WrappedResponse.decode(data)
response = wrapped_response.response
# Raise error replies
if response.is_a?(Warden::Protocol::ErrorResponse)
raise Warden::Client::ServerError.new(response.message)
end
if @v1mode
response = V1.response_to_v1(response)
end
response
end
def write(request)
if request.kind_of?(Array)
@v1mode = true
request = V1.request_from_v1(request.dup)
end
unless request.kind_of?(Warden::Protocol::BaseRequest)
raise "Expected #kind_of? Warden::Protocol::BaseRequest"
end
data = request.wrap.encode.to_s
@sock.write data.length.to_s + "\r\n"
@sock.write data + "\r\n"
end
def stream(request, &blk)
unless request.is_a?(Warden::Protocol::StreamRequest)
msg = "Expected argument to be of type:"
msg << "'#{Warden::Protocol::StreamRequest}'"
msg << ", but received: '#{request.class}'."
raise ArgumentError, msg
end
response = call(request)
while response.exit_status.nil?
blk.call(response)
response = read
end
response
end
def call(request)
write(request)
read
end
def method_missing(sym, *args, &blk)
klass_name = sym.to_s.gsub(/(^|_)([a-z])/) { $2.upcase }
klass_name += "Request"
klass = Warden::Protocol.const_get(klass_name)
call(klass.new(*args))
end
end
end