This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
/
client.rb
263 lines (207 loc) · 6.28 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
require "nats/rpc/peer"
require "nats/rpc/util/event_emitter"
module NATS
module RPC
class Client < Peer
def post_initialize
subscribe(base_subject + ".inbox.#{peer_id}") do |message|
request = @registry[message["message_id"]]
if request
reply = Reply.new(request, message)
request.emit("reply", reply)
end
end
# Initialize registry mapping message IDs to calls with a pending reply.
# Request objects are responsible for removing themselves from the registry
# once they time out, or are otherwise cancelled.
@registry = {}
end
def register(request)
@registry[request.message_id] = request
end
def unregister(request)
@registry.delete(request.message_id)
end
def registered?(request)
@registry.has_key?(request.message_id)
end
def call(peer_id, method, payload = nil, options = {}, &blk)
request = Call.new(self, method, payload, options)
request.peer_id = peer_id
request.shortcut!(&blk) if blk
request
end
def mcall(method, payload = nil, options = {}, &blk)
request = Mcall.new(self, method, payload, options)
request.shortcut!(&blk) if blk
request
end
def mcast(method, payload = nil, options = {})
Mcast.new(self, method, payload, options)
end
def generate_message_id
@message_id ||= 0
@message_id += 1
end
class Request
include Util::EventEmitter
attr_reader :client
attr_reader :message_id
attr_reader :method
attr_reader :options
def initialize(client, method, payload, options = {})
@client = client
@method = client.service.class.methods[method.to_s]
@payload = payload
# The service should export the specified method
if @method.nil?
raise ArgumentError.new("non-exisiting method specified")
end
# This is toggled when the request is executed
@in_progress = false
# Override the method's default options with the passed options
@options = @method.options.merge(options)
post_initialize
end
# Placeholder.
def post_initialize; end
# Generate message ID on-demand.
def message_id
@message_id ||= client.generate_message_id
end
# Construct minimal message for this request.
def message
{ "message_id" => message_id,
"peer_id" => client.peer_id,
"method" => @method.name,
"payload" => @payload }
end
def generate_subject(*parts)
[client.base_subject, parts].flatten.join(".")
end
# Register this request with the client, so it can dispatch
# corresponding replies to this request object.
def register
client.register(self)
end
# Unregister this request with the client. Replys that arrive after
# doing this are no longer dispatched to this request object.
def unregister
client.unregister(self)
end
# Is this request registered to receive more replies?
def registered?
client.registered?(self)
end
# Verify if the call is valid. For a call to be valid, the method
# should exist. Other properties that determine if a call is valid may
# be added in the future.
def valid?
true
end
protected
def prepare_execute
raise "invalid request" unless valid?
raise "already in progress or finished" if @in_progress
@in_progress = true
end
end
class ExpectReplyRequest < Request
# All requests should finish sometime... Requests without a timeout
# otherwise hang around in the client's registry forever, unless
# explicitly unregistered by the user.
DEFAULT_TIMEOUT = 30
attr_accessor :timeout
def initialize(*args)
super
@timeout = options[:timeout] || method.options[:timeout] || DEFAULT_TIMEOUT
@timer = nil
end
def shortcut!(&blk)
on("reply") { |reply|
blk.call(self, reply)
}
on("timeout") {
blk.call(self, nil)
}
execute!
end
def register
super
start_timer
end
def unregister
super
stop_timer
end
protected
def prepare_execute
super
register
end
def start_timer
if @timeout
# Unregister for new replies and emit event after timing out
@timer = ::EM::Timer.new(@timeout) {
emit("timeout")
unregister
}
end
end
def stop_timer
if @timer
@timer.cancel
@timer = nil
end
end
end
class Call < ExpectReplyRequest
attr_accessor :peer_id
def execute!
prepare_execute
client.publish(generate_subject("call", peer_id), message)
# Unregister after receiving the first reply.
on("reply") {
unregister
}
end
end
class Mcall < ExpectReplyRequest
def execute!
prepare_execute
client.publish(generate_subject("mcall"), message)
end
end
class Mcast < Request
def execute!
prepare_execute
client.publish(generate_subject("mcast"), message)
end
end
class Reply
# Base
attr_reader :request
attr_reader :message_id
# Meta
attr_reader :peer_id
def initialize(request, message)
@request = request
@message = message
end
def message_id
@message["message_id"]
end
def peer_id
@message["peer_id"]
end
def result
if @message["error"]
raise Service::Error.from_hash(@message["error"])
else
@message["payload"]
end
end
end
end
end # module RPC
end # module NATS