beaneater 1.1.4 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.github/workflows/ruby.yml +7 -3
- data/CHANGELOG.md +28 -0
- data/Gemfile +1 -1
- data/README.md +34 -1
- data/Rakefile +55 -0
- data/beaneater.gemspec +8 -1
- data/lib/beaneater/arguments.rb +66 -0
- data/lib/beaneater/configuration.rb +8 -0
- data/lib/beaneater/connection.rb +322 -61
- data/lib/beaneater/errors.rb +14 -0
- data/lib/beaneater/job/collection.rb +45 -7
- data/lib/beaneater/job/record.rb +17 -8
- data/lib/beaneater/stats/fast_struct.rb +7 -0
- data/lib/beaneater/stats/stat_struct.rb +8 -2
- data/lib/beaneater/stats.rb +6 -0
- data/lib/beaneater/tube/collection.rb +8 -6
- data/lib/beaneater/tube/record.rb +6 -5
- data/lib/beaneater/version.rb +1 -1
- data/lib/beaneater.rb +1 -1
- data/test/arguments_test.rb +174 -0
- data/test/connection_test.rb +628 -16
- data/test/job_test.rb +36 -0
- data/test/jobs_test.rb +440 -0
- data/test/stat_struct_test.rb +30 -0
- data/test/stats_test.rb +16 -0
- data/test/test_helper.rb +45 -0
- data/test/tube_test.rb +123 -0
- data/test/tubes_test.rb +30 -1
- metadata +12 -6
- data/.travis.yml +0 -15
data/lib/beaneater/connection.rb
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
require 'yaml'
|
|
4
4
|
require 'socket'
|
|
5
|
+
require 'io/wait'
|
|
6
|
+
require 'monitor'
|
|
5
7
|
|
|
6
8
|
class Beaneater
|
|
7
9
|
# Represents a connection to a beanstalkd instance.
|
|
@@ -13,6 +15,15 @@ class Beaneater
|
|
|
13
15
|
# Default retry interval
|
|
14
16
|
DEFAULT_RETRY_INTERVAL = 1
|
|
15
17
|
|
|
18
|
+
# Fields of the stats responses that are text even when they look numeric
|
|
19
|
+
# (a tube named "1.12", a server id made only of digits). beanstalkd 1.13
|
|
20
|
+
# quotes most of these, 1.12 does not.
|
|
21
|
+
STRING_STAT_FIELDS = {
|
|
22
|
+
'stats' => %w(version id hostname os platform),
|
|
23
|
+
'stats-job' => %w(tube state),
|
|
24
|
+
'stats-tube' => %w(name)
|
|
25
|
+
}.freeze
|
|
26
|
+
|
|
16
27
|
# @!attribute address
|
|
17
28
|
# @return [String] returns Beanstalkd server address
|
|
18
29
|
# @example
|
|
@@ -52,7 +63,10 @@ class Beaneater
|
|
|
52
63
|
#
|
|
53
64
|
def initialize(address)
|
|
54
65
|
@address = address || _host_from_env || Beaneater.configuration.beanstalkd_url
|
|
55
|
-
|
|
66
|
+
# Held for each attempt at a command (reconnecting and restoring the tubes included), not
|
|
67
|
+
# across the pauses between attempts. Reentrant: a job_parser that uses this client runs
|
|
68
|
+
# while its command holds the lock.
|
|
69
|
+
@mutex = Monitor.new
|
|
56
70
|
@tube_used = 'default'
|
|
57
71
|
@tubes_watched = ['default']
|
|
58
72
|
|
|
@@ -72,16 +86,27 @@ class Beaneater
|
|
|
72
86
|
# @conn.transmit('stats')
|
|
73
87
|
#
|
|
74
88
|
def transmit(command, **options)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
89
|
+
state = {
|
|
90
|
+
:retry_interval => options[:retry_interval] || DEFAULT_RETRY_INTERVAL, # nil too
|
|
91
|
+
:init => options.fetch(:init, true),
|
|
92
|
+
:reconnects => 0,
|
|
93
|
+
:connect_tries => MAX_RETRIES,
|
|
94
|
+
:draining_tries => MAX_RETRIES,
|
|
95
|
+
:connecting => false
|
|
96
|
+
}
|
|
97
|
+
reentrant = @mutex.mon_owned?
|
|
98
|
+
loop do
|
|
99
|
+
done, value = @mutex.synchronize { _attempt(command, state) }
|
|
100
|
+
return value if done
|
|
101
|
+
# Pause before the next attempt with the lock released, so other threads go on and
|
|
102
|
+
# Timeout or Thread#raise can stop this one. A reentrant call (from a job_parser) still
|
|
103
|
+
# holds its outer command's lock here.
|
|
104
|
+
sleep(value)
|
|
84
105
|
end
|
|
106
|
+
ensure
|
|
107
|
+
# #close during a command (from its job_parser, a signal handler or another thread) only
|
|
108
|
+
# shut the socket down; close it once the command is over and nothing waits on it
|
|
109
|
+
@mutex.synchronize { _drop_connection if @closed && @connection } if @closed && !reentrant
|
|
85
110
|
end
|
|
86
111
|
|
|
87
112
|
# Close connection with beanstalkd server.
|
|
@@ -90,10 +115,31 @@ class Beaneater
|
|
|
90
115
|
# @conn.close
|
|
91
116
|
#
|
|
92
117
|
def close
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
118
|
+
@closed = true
|
|
119
|
+
socket = @connection
|
|
120
|
+
if @mutex.mon_locked? && @connection_pid == Process.pid
|
|
121
|
+
# A thread (this one or another) is inside a command and may be waiting on the socket.
|
|
122
|
+
# IO#close from a signal handler while any thread waits on that IO can crash Ruby 3.3
|
|
123
|
+
# and 3.4 (segfault in IO#wait_readable) or raise ThreadError. Shut it down instead:
|
|
124
|
+
# the wait ends with end-of-file, the command raises NotConnected, and its transmit
|
|
125
|
+
# closes the socket on its way out. Only in the process that opened the connection: a
|
|
126
|
+
# child forked during a command inherits the held lock, and shutting down would cut
|
|
127
|
+
# the parent's connection; the child just closes its own copy below.
|
|
128
|
+
socket.shutdown(Socket::SHUT_RDWR) if socket && !socket.closed?
|
|
129
|
+
else
|
|
130
|
+
# ceiling: a thread can take the lock between the check above and this close and start
|
|
131
|
+
# waiting on the socket. A close from a signal handler then raises ThreadError on Ruby
|
|
132
|
+
# 3.3 and 3.4 (ignored below); the waiting thread gets a TypeError from Ruby, and Ruby
|
|
133
|
+
# keeps the fd open (and the server that connection's pending command) until garbage
|
|
134
|
+
# collection. On 3.1, 3.2 and 4.0, and from a plain thread, the waiter gets IOError.
|
|
135
|
+
# Closing under the lock would shut the window, but a signal handler cannot wait for
|
|
136
|
+
# the lock.
|
|
137
|
+
_drop_connection
|
|
96
138
|
end
|
|
139
|
+
rescue ThreadError
|
|
140
|
+
nil # IO#close refused in a signal handler (see the ceiling above)
|
|
141
|
+
rescue SystemCallError, IOError
|
|
142
|
+
nil # already disconnected, or closed by another thread meanwhile
|
|
97
143
|
end
|
|
98
144
|
|
|
99
145
|
# Returns string representation of job.
|
|
@@ -106,13 +152,15 @@ class Beaneater
|
|
|
106
152
|
end
|
|
107
153
|
alias :inspect :to_s
|
|
108
154
|
|
|
155
|
+
# The watched tubes are kept by name, once each: a reconnect watches them again.
|
|
109
156
|
def add_to_watched(tube_name)
|
|
110
|
-
@tubes_watched << tube_name
|
|
111
|
-
@tubes_watched.uniq
|
|
157
|
+
@tubes_watched << tube_name.to_s
|
|
158
|
+
@tubes_watched.uniq!
|
|
159
|
+
@tubes_watched
|
|
112
160
|
end
|
|
113
161
|
|
|
114
162
|
def remove_from_watched(tube_name)
|
|
115
|
-
@tubes_watched.delete(tube_name)
|
|
163
|
+
@tubes_watched.delete(tube_name.to_s)
|
|
116
164
|
end
|
|
117
165
|
|
|
118
166
|
protected
|
|
@@ -129,7 +177,17 @@ class Beaneater
|
|
|
129
177
|
match = address.split(':')
|
|
130
178
|
@host, @port = match[0], Integer(match[1] || DEFAULT_PORT)
|
|
131
179
|
|
|
132
|
-
|
|
180
|
+
tcp_opts = { connect_timeout: config.connect_timeout, resolv_timeout: config.resolv_timeout }.compact
|
|
181
|
+
|
|
182
|
+
socket = if RUBY_VERSION >= "3.0" && tcp_opts.any?
|
|
183
|
+
TCPSocket.new(@host, @port, **tcp_opts)
|
|
184
|
+
else
|
|
185
|
+
TCPSocket.new(@host, @port)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
@read_buffer = String.new # binary; bytes read but not yet consumed
|
|
189
|
+
@connection = socket
|
|
190
|
+
@connection_pid = Process.pid # a forked child shares the socket; see #close
|
|
133
191
|
end
|
|
134
192
|
|
|
135
193
|
# Parses the response and returns the useful beanstalk response.
|
|
@@ -151,15 +209,17 @@ class Beaneater
|
|
|
151
209
|
body = nil
|
|
152
210
|
if ['OK','FOUND', 'RESERVED'].include?(status)
|
|
153
211
|
bytes_size = body_values[-1].to_i
|
|
154
|
-
raw_body =
|
|
212
|
+
raw_body = _read_bytes(bytes_size, cmd)
|
|
213
|
+
# Consume the trailing CRLF before parsing, so a parser that raises
|
|
214
|
+
# leaves the stream at the start of the next reply.
|
|
215
|
+
crlf = _read_bytes(2, cmd) # \r\n
|
|
216
|
+
raise ExpectedCrlfError.new('EXPECTED_CRLF', cmd) if crlf != "\r\n"
|
|
217
|
+
@reply_read = true
|
|
155
218
|
body = if status == 'OK'
|
|
156
|
-
|
|
157
|
-
YAML.load(psych_v4_valid_body)
|
|
219
|
+
parse_yaml_body(cmd, raw_body)
|
|
158
220
|
else
|
|
159
|
-
|
|
221
|
+
_parse_job(status, body_values[1], raw_body)
|
|
160
222
|
end
|
|
161
|
-
crlf = connection.read(2) # \r\n
|
|
162
|
-
raise ExpectedCrlfError.new('EXPECTED_CRLF', cmd) if crlf != "\r\n"
|
|
163
223
|
end
|
|
164
224
|
id = body_values[1]
|
|
165
225
|
response = { :status => status }
|
|
@@ -168,6 +228,57 @@ class Beaneater
|
|
|
168
228
|
response
|
|
169
229
|
end
|
|
170
230
|
|
|
231
|
+
# Parses the YAML body of an OK response (stats, stats-job, stats-tube,
|
|
232
|
+
# list-tubes, list-tubes-watched). beanstalkd emits only a "---" line
|
|
233
|
+
# followed by "key: value" lines or "- item" lines, so the body is parsed
|
|
234
|
+
# directly rather than through a YAML loader, which would turn tube names
|
|
235
|
+
# such as "2022-09-30", "1.12" or "true" into dates, numbers or booleans.
|
|
236
|
+
#
|
|
237
|
+
# @param [String] cmd Beanstalk command transmitted
|
|
238
|
+
# @param [String] raw_body Response body
|
|
239
|
+
# @return [Hash{String => String, Integer, Float, Boolean}, Array<String>] Parsed body
|
|
240
|
+
# @example
|
|
241
|
+
# parse_yaml_body("stats-job 1", "---\nid: 1\ntube: email-jobs\n")
|
|
242
|
+
# # => { "id" => 1, "tube" => "email-jobs" }
|
|
243
|
+
#
|
|
244
|
+
def parse_yaml_body(cmd, raw_body)
|
|
245
|
+
lines = raw_body.dup.force_encoding(Encoding::UTF_8).each_line.map(&:chomp)
|
|
246
|
+
lines.shift if lines.first == '---'
|
|
247
|
+
if lines.first && lines.first.start_with?('- ')
|
|
248
|
+
lines.map { |line| _stat_value(line[2..-1], true) }
|
|
249
|
+
else
|
|
250
|
+
text_fields = STRING_STAT_FIELDS[cmd.to_s.split(' ').first] || []
|
|
251
|
+
lines.each_with_object({}) do |line, hash|
|
|
252
|
+
key, value = line.split(': ', 2)
|
|
253
|
+
hash[key] = _stat_value(value.to_s, text_fields.include?(key)) unless key.to_s.empty?
|
|
254
|
+
end
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# Runs the job_parser on a job's body. If it raises for a job this connection has just
|
|
259
|
+
# reserved, a copy of the parser's exception is raised instead (same class, message,
|
|
260
|
+
# backtrace and cause, so `rescue JSON::ParserError` still works), tagged with
|
|
261
|
+
# Beaneater::JobParseFailure, which gives the job's id: Jobs#process! uses it to bury the job
|
|
262
|
+
# instead of leaving it reserved until its TTR. A copy, so that an exception the parser
|
|
263
|
+
# froze or raises again later is never changed or tagged with an old id.
|
|
264
|
+
def _parse_job(status, id, raw_body)
|
|
265
|
+
config.job_parser.call(raw_body)
|
|
266
|
+
rescue StandardError => ex
|
|
267
|
+
raise unless status == 'RESERVED'
|
|
268
|
+
begin
|
|
269
|
+
tagged = ex.clone(:freeze => false)
|
|
270
|
+
tagged.extend(JobParseFailure)
|
|
271
|
+
tagged.job_id = id
|
|
272
|
+
cause = ex.cause
|
|
273
|
+
rescue StandardError
|
|
274
|
+
tagged = nil # it can't be copied (an initialize_clone or initialize_copy of its own)
|
|
275
|
+
end
|
|
276
|
+
# Re-raised out here, where $! is still ex: raised inside the rescue above, a frozen ex
|
|
277
|
+
# would get the copying error as its cause and fail with "circular causes".
|
|
278
|
+
raise ex unless tagged
|
|
279
|
+
raise tagged, :cause => (cause if cause.is_a?(Exception))
|
|
280
|
+
end
|
|
281
|
+
|
|
171
282
|
# Returns configuration options for beaneater
|
|
172
283
|
#
|
|
173
284
|
# @return [Beaneater::Configuration] configuration object
|
|
@@ -177,57 +288,111 @@ class Beaneater
|
|
|
177
288
|
|
|
178
289
|
private
|
|
179
290
|
|
|
291
|
+
# Sends one command and reads its whole reply, without retrying.
|
|
292
|
+
def _exchange(command)
|
|
293
|
+
completed = false
|
|
294
|
+
outer_reply_read = @reply_read # a job_parser that uses this client runs an _exchange inside ours
|
|
295
|
+
@reply_read = false # set by parse_response once the whole reply is off the socket
|
|
296
|
+
unless connection
|
|
297
|
+
_raise_not_connected! if @closed
|
|
298
|
+
raise Errno::ENOTCONN # _attempt reconnects and restores the tubes first
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
command = command.dup.force_encoding('ASCII-8BIT') if command.respond_to?(:force_encoding)
|
|
302
|
+
read_window = _read_window(command) # checked before anything is written
|
|
303
|
+
_write(command.to_s + "\r\n", command)
|
|
304
|
+
@read_deadline = _deadline_in(read_window) # bounds the status line and the body read in parse_response
|
|
305
|
+
res = _read_line(command)
|
|
306
|
+
response = parse_response(command, res)
|
|
307
|
+
completed = true
|
|
308
|
+
response
|
|
309
|
+
rescue UnexpectedResponse => ex
|
|
310
|
+
# an error status line is the whole reply, so the stream is still in step
|
|
311
|
+
completed = !ex.is_a?(ExpectedCrlfError)
|
|
312
|
+
raise
|
|
313
|
+
ensure
|
|
314
|
+
# Interrupted between the write and the end of the reply (Timeout, Interrupt, an I/O
|
|
315
|
+
# error): the rest of the reply may still arrive, so drop the socket rather than let the
|
|
316
|
+
# next command read it. The next command reconnects. Once the whole reply has been read
|
|
317
|
+
# (a job_parser that raised, say) the stream is in step: keep the socket, and with it the
|
|
318
|
+
# jobs this connection has reserved.
|
|
319
|
+
_drop_connection unless completed || @reply_read
|
|
320
|
+
@reply_read = outer_reply_read
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
# Restores the watched and used tubes on a new connection. Sent with _exchange, not transmit:
|
|
324
|
+
# a failure here must go back to the _attempt that is reconnecting, which starts over.
|
|
180
325
|
def _initialize_tubes
|
|
181
326
|
if @tubes_watched != ['default']
|
|
182
327
|
tubes_watched.each do |t|
|
|
183
|
-
|
|
328
|
+
_exchange("watch #{Arguments.tube_name(t)}")
|
|
184
329
|
end
|
|
185
330
|
|
|
186
|
-
|
|
331
|
+
_exchange("ignore default") unless tubes_watched.include?('default')
|
|
187
332
|
end
|
|
188
333
|
|
|
189
|
-
|
|
334
|
+
_exchange("use #{Arguments.tube_name(tube_used)}") if @tube_used != 'default'
|
|
190
335
|
end
|
|
191
336
|
|
|
192
|
-
#
|
|
193
|
-
#
|
|
194
|
-
#
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
337
|
+
# One attempt at a command, made holding the lock: reconnect (and restore the tubes) if the
|
|
338
|
+
# connection is gone, then send the command. Returns [true, response], or [false, seconds]
|
|
339
|
+
# to pause and try again. state carries the retry counts across attempts.
|
|
340
|
+
def _attempt(command, state)
|
|
341
|
+
if connection
|
|
342
|
+
state[:connecting] = false # another thread may have reconnected during our pause
|
|
343
|
+
else
|
|
344
|
+
_raise_not_connected! if @closed
|
|
345
|
+
unless state[:connecting] # a new reconnect, not the next try of one in progress
|
|
346
|
+
state[:reconnects] += 1
|
|
347
|
+
# something accepts connections but drops every command (a proxy with no backend):
|
|
348
|
+
# give up rather than reconnect in a tight loop
|
|
349
|
+
_raise_not_connected! if state[:reconnects] > MAX_RETRIES
|
|
350
|
+
state[:connecting] = true
|
|
351
|
+
state[:connect_tries] = MAX_RETRIES
|
|
352
|
+
end
|
|
353
|
+
begin
|
|
354
|
+
establish_connection
|
|
355
|
+
rescue SystemCallError, SocketError, IOError
|
|
356
|
+
state[:connect_tries] -= 1
|
|
357
|
+
_raise_not_connected! if state[:connect_tries].zero?
|
|
358
|
+
return [false, state[:retry_interval]]
|
|
359
|
+
end
|
|
360
|
+
state[:connecting] = false
|
|
361
|
+
if @closed # #close ran while connecting
|
|
362
|
+
_drop_connection
|
|
363
|
+
_raise_not_connected!
|
|
364
|
+
end
|
|
365
|
+
if state[:init]
|
|
366
|
+
begin
|
|
367
|
+
_initialize_tubes
|
|
368
|
+
rescue Exception
|
|
369
|
+
# never leave a half-restored connection watching the wrong tubes: drop it, so a
|
|
370
|
+
# lost connection reconnects and restores again below, and anything else makes the
|
|
371
|
+
# next command start over
|
|
372
|
+
_drop_connection
|
|
373
|
+
raise
|
|
374
|
+
end
|
|
375
|
+
end
|
|
376
|
+
end
|
|
377
|
+
[true, _exchange(command)]
|
|
378
|
+
rescue EOFError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ENOTCONN
|
|
379
|
+
_drop_connection
|
|
380
|
+
retry # reconnects at once, still holding the lock
|
|
206
381
|
rescue Beaneater::DrainingError
|
|
207
|
-
|
|
208
|
-
if
|
|
209
|
-
|
|
382
|
+
state[:draining_tries] -= 1
|
|
383
|
+
if state[:draining_tries].zero?
|
|
384
|
+
_drop_connection
|
|
210
385
|
raise
|
|
211
386
|
end
|
|
212
|
-
|
|
213
|
-
retry
|
|
387
|
+
[false, state[:retry_interval]]
|
|
214
388
|
end
|
|
215
389
|
|
|
216
|
-
#
|
|
217
|
-
#
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
close
|
|
223
|
-
establish_connection
|
|
224
|
-
rescue Errno::ECONNREFUSED
|
|
225
|
-
tries -= 1
|
|
226
|
-
if tries.zero?
|
|
227
|
-
_raise_not_connected!
|
|
228
|
-
end
|
|
229
|
-
sleep(retry_interval || DEFAULT_RETRY_INTERVAL)
|
|
230
|
-
retry
|
|
390
|
+
# Closes the socket without marking the connection closed, so the next command reconnects.
|
|
391
|
+
# Only #close is final.
|
|
392
|
+
def _drop_connection
|
|
393
|
+
socket, @connection = @connection, nil
|
|
394
|
+
@read_buffer = String.new
|
|
395
|
+
socket.close if socket
|
|
231
396
|
end
|
|
232
397
|
|
|
233
398
|
# The host provided by BEANSTALKD_URL environment variable, if available.
|
|
@@ -241,10 +406,106 @@ class Beaneater
|
|
|
241
406
|
ENV['BEANSTALKD_URL'].respond_to?(:length) && ENV['BEANSTALKD_URL'].length > 0 && ENV['BEANSTALKD_URL'].strip
|
|
242
407
|
end
|
|
243
408
|
|
|
409
|
+
# Converts one value of a stats or list response to its Ruby type:
|
|
410
|
+
# quoted values and text fields stay Strings, whole numbers become
|
|
411
|
+
# Integers, decimals Floats, and true/false Booleans.
|
|
412
|
+
def _stat_value(value, text)
|
|
413
|
+
if value.length >= 2 && value.start_with?('"') && value.end_with?('"')
|
|
414
|
+
value[1..-2]
|
|
415
|
+
elsif text
|
|
416
|
+
value
|
|
417
|
+
elsif value =~ /\A-?\d+\z/
|
|
418
|
+
value.to_i
|
|
419
|
+
elsif value =~ /\A-?\d+\.\d+\z/
|
|
420
|
+
value.to_f
|
|
421
|
+
elsif value == 'true' || value == 'false'
|
|
422
|
+
value == 'true'
|
|
423
|
+
else
|
|
424
|
+
value
|
|
425
|
+
end
|
|
426
|
+
end
|
|
427
|
+
|
|
428
|
+
# Writes data to the socket, waiting at most write_timeout seconds.
|
|
429
|
+
#
|
|
430
|
+
# Ruby waits on its sockets itself, so the socket-level SO_SNDTIMEO and
|
|
431
|
+
# SO_RCVTIMEO options have no effect; the deadlines are kept here instead.
|
|
432
|
+
def _write(data, cmd)
|
|
433
|
+
deadline = _deadline_in(config.write_timeout && Float(config.write_timeout))
|
|
434
|
+
until data.empty?
|
|
435
|
+
written = connection.write_nonblock(data, exception: false)
|
|
436
|
+
if written == :wait_writable
|
|
437
|
+
_wait_for(:write, deadline, cmd)
|
|
438
|
+
else
|
|
439
|
+
data = data.byteslice(written..-1)
|
|
440
|
+
end
|
|
441
|
+
end
|
|
442
|
+
end
|
|
443
|
+
|
|
444
|
+
# Returns how many seconds the reply to cmd may take once it is written, or
|
|
445
|
+
# nil to wait without limit. reserve-with-timeout gets its own timeout on top
|
|
446
|
+
# of read_timeout; a plain reserve blocks until a job arrives, by design.
|
|
447
|
+
# Timeouts may be given as numeric strings (from ENV, say).
|
|
448
|
+
def _read_window(cmd)
|
|
449
|
+
return nil if config.read_timeout.nil? || cmd =~ /\Areserve\s*\z/
|
|
450
|
+
extra = cmd =~ /\Areserve-with-timeout (\d+)/ ? $1.to_i : 0
|
|
451
|
+
Float(config.read_timeout) + extra
|
|
452
|
+
end
|
|
453
|
+
|
|
454
|
+
# Reads one reply line (the status line), without its line ending.
|
|
455
|
+
def _read_line(cmd)
|
|
456
|
+
until (eol = @read_buffer.index("\n"))
|
|
457
|
+
_fill_read_buffer(cmd)
|
|
458
|
+
end
|
|
459
|
+
@read_buffer.slice!(0, eol + 1)
|
|
460
|
+
end
|
|
461
|
+
|
|
462
|
+
# Reads exactly size bytes of a reply body.
|
|
463
|
+
def _read_bytes(size, cmd)
|
|
464
|
+
_fill_read_buffer(cmd) while @read_buffer.bytesize < size
|
|
465
|
+
@read_buffer.slice!(0, size)
|
|
466
|
+
end
|
|
467
|
+
|
|
468
|
+
# Waits until the socket has data (up to the reply's deadline) and appends
|
|
469
|
+
# what is available to the read buffer.
|
|
470
|
+
def _fill_read_buffer(cmd)
|
|
471
|
+
_wait_for(:read, @read_deadline, cmd)
|
|
472
|
+
@read_buffer << connection.readpartial(16_384)
|
|
473
|
+
end
|
|
474
|
+
|
|
475
|
+
# Waits for the socket to become readable or writable before deadline.
|
|
476
|
+
# On timeout the connection is dropped (the next command reconnects): a late
|
|
477
|
+
# reply would otherwise be read as the answer to the next command.
|
|
478
|
+
#
|
|
479
|
+
# @raise [Beaneater::SocketTimeout] The deadline passed.
|
|
480
|
+
def _wait_for(direction, deadline, cmd)
|
|
481
|
+
# Past the deadline this still polls once (timeout 0): data that is already there is
|
|
482
|
+
# not a timeout.
|
|
483
|
+
remaining = deadline && [deadline - _now, 0].max
|
|
484
|
+
# IO#wait_* rather than IO.select: a thread waiting here is woken by end-of-file when
|
|
485
|
+
# #close shuts the socket down (its command then raises NotConnected).
|
|
486
|
+
ready = direction == :read ? connection.wait_readable(remaining) : connection.wait_writable(remaining)
|
|
487
|
+
return if ready
|
|
488
|
+
|
|
489
|
+
_drop_connection
|
|
490
|
+
action = direction == :read ? 'waiting for the reply to' : 'writing'
|
|
491
|
+
raise SocketTimeout, "Timed out #{action} '#{cmd.to_s.split("\r\n").first}' on beanstalk '#{@host}:#{@port}'; the next command reconnects"
|
|
492
|
+
end
|
|
493
|
+
|
|
494
|
+
def _deadline_in(seconds)
|
|
495
|
+
seconds && _now + seconds
|
|
496
|
+
end
|
|
497
|
+
|
|
498
|
+
def _now
|
|
499
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
500
|
+
end
|
|
501
|
+
|
|
244
502
|
# Raises an error to be triggered when the connection has failed
|
|
245
503
|
# @raise [Beaneater::NotConnected] Beanstalkd is no longer connected
|
|
246
504
|
def _raise_not_connected!
|
|
247
|
-
|
|
505
|
+
# host and port stay unset for an address establish_connection can't parse: name it as given,
|
|
506
|
+
# leaving out any user and password (user:password@)
|
|
507
|
+
where = (@host ? "#{@host}:#{@port}" : @address.to_s).sub(%r{\A(\w[\w+.-]*://)?.*@}m, '\1')
|
|
508
|
+
raise Beaneater::NotConnected, "Connection to beanstalk '#{where}' is closed!"
|
|
248
509
|
end
|
|
249
510
|
|
|
250
511
|
end # Connection
|
data/lib/beaneater/errors.rb
CHANGED
|
@@ -3,6 +3,20 @@
|
|
|
3
3
|
class Beaneater
|
|
4
4
|
# Raises when a beanstalkd instance is no longer accessible.
|
|
5
5
|
class NotConnected < RuntimeError; end
|
|
6
|
+
# Raises when beanstalkd does not answer within the configured read_timeout,
|
|
7
|
+
# or a command cannot be written within write_timeout. The connection is
|
|
8
|
+
# closed, since a late reply would otherwise be read as the answer to the
|
|
9
|
+
# next command. Not to be confused with {TimedOutError}, which is
|
|
10
|
+
# beanstalkd's own TIMED_OUT reply to reserve-with-timeout.
|
|
11
|
+
class SocketTimeout < NotConnected; end
|
|
12
|
+
# Added to a copy of the exception a job_parser raises for a job just reserved. The copy
|
|
13
|
+
# keeps the exception's class (JSON::ParserError, say), message, backtrace and cause; #job_id
|
|
14
|
+
# names the job, still reserved by this connection, so the caller can bury, release or
|
|
15
|
+
# delete it.
|
|
16
|
+
module JobParseFailure
|
|
17
|
+
# @return [String] id of the reserved job whose body the parser rejected
|
|
18
|
+
attr_accessor :job_id
|
|
19
|
+
end
|
|
6
20
|
# Raises when the tube name specified is invalid.
|
|
7
21
|
class InvalidTubeName < RuntimeError; end
|
|
8
22
|
# Raises when a job has not been reserved properly.
|
|
@@ -53,7 +53,7 @@ class Beaneater
|
|
|
53
53
|
#
|
|
54
54
|
# @api public
|
|
55
55
|
def find(id)
|
|
56
|
-
res = transmit("peek #{id}")
|
|
56
|
+
res = transmit("peek #{Arguments.integer(id, 'job id')}")
|
|
57
57
|
Job.new(client, res)
|
|
58
58
|
rescue Beaneater::NotFoundError
|
|
59
59
|
nil
|
|
@@ -103,15 +103,30 @@ class Beaneater
|
|
|
103
103
|
# @param [Hash{String => Integer}] options Settings for processing
|
|
104
104
|
# @option options [Integer] release_delay Delay in seconds before to make job ready again
|
|
105
105
|
# @option options [Integer] reserve_timeout Number of seconds to wait for a job before checking a different server
|
|
106
|
+
# @raise [ArgumentError] No processor is registered (see {#register}).
|
|
106
107
|
#
|
|
107
108
|
# @api public
|
|
108
109
|
def process!(options={})
|
|
110
|
+
raise ArgumentError, "no processors registered: call jobs.register(tube_name) { |job| ... } first" unless processors
|
|
109
111
|
release_delay = options.delete(:release_delay) || RELEASE_DELAY
|
|
110
112
|
reserve_timeout = options.delete(:reserve_timeout) || RESERVE_TIMEOUT
|
|
111
113
|
client.tubes.watch!(*processors.keys)
|
|
112
114
|
while !stop? do
|
|
113
115
|
begin
|
|
114
|
-
@current_job =
|
|
116
|
+
@current_job = nil # never take an earlier iteration's job for this one
|
|
117
|
+
begin
|
|
118
|
+
@current_job = client.tubes.reserve(reserve_timeout)
|
|
119
|
+
rescue Beaneater::JobParseFailure => ex
|
|
120
|
+
# The job_parser rejected the job just reserved, so there was no job to handle: it is
|
|
121
|
+
# ours to bury (the ensure below does), whatever the parser raised, rather than leave
|
|
122
|
+
# it reserved to be released and fail again when its TTR runs out.
|
|
123
|
+
# ceiling: a parser exception that can't be copied is raised untagged, so process!
|
|
124
|
+
# can't tell which job it came from; the job stays reserved, and near its TTR process!
|
|
125
|
+
# keeps reserving (DEADLINE_SOON) until beanstalkd releases it, then fails on it again.
|
|
126
|
+
# Upgrade path: have the connection record the id of the job whose parse failed.
|
|
127
|
+
@current_job = Job.new(client, :id => ex.job_id, :status => 'RESERVED')
|
|
128
|
+
raise
|
|
129
|
+
end
|
|
115
130
|
processor = processors[@current_job.tube]
|
|
116
131
|
begin
|
|
117
132
|
processor[:block].call(@current_job)
|
|
@@ -124,14 +139,37 @@ class Beaneater
|
|
|
124
139
|
rescue AbortProcessingError
|
|
125
140
|
break
|
|
126
141
|
rescue Beaneater::JobNotReserved, Beaneater::NotFoundError, Beaneater::TimedOutError
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
142
|
+
# No job yet (reserve timed out), or the job is gone (its handler deleted or released
|
|
143
|
+
# it, or its TTR ran out). If a handler or the job_parser raised this with the job still
|
|
144
|
+
# reserved, the ensure buries that job like any failure; then the loop goes on.
|
|
145
|
+
nil
|
|
146
|
+
rescue Beaneater::NotConnected
|
|
147
|
+
# Only when this client's own connection is gone (reconnecting failed, or it was
|
|
148
|
+
# closed): the server releases a job reserved on it. A NotConnected from a handler that
|
|
149
|
+
# uses another client is a failed job like any other, buried by the ensure below.
|
|
150
|
+
unless client.connection.connection
|
|
151
|
+
@current_job = nil
|
|
152
|
+
raise
|
|
153
|
+
end
|
|
154
|
+
rescue StandardError # handles unspecified errors: the ensure below buries the job
|
|
130
155
|
ensure # bury if still reserved
|
|
131
|
-
|
|
132
|
-
|
|
156
|
+
begin
|
|
157
|
+
bury_if_reserved(@current_job)
|
|
158
|
+
ensure
|
|
159
|
+
@current_job = nil # even when burying fails, so no later loop sees this job
|
|
160
|
+
end
|
|
133
161
|
end
|
|
134
162
|
end
|
|
135
163
|
end # process!
|
|
164
|
+
|
|
165
|
+
private
|
|
166
|
+
|
|
167
|
+
# Buries a job this worker still holds. NOT_FOUND means it no longer holds it (the handler
|
|
168
|
+
# deleted it, or its TTR ran out and the server released it), so there is nothing to bury.
|
|
169
|
+
def bury_if_reserved(job)
|
|
170
|
+
job.bury if job && job.exists? && job.reserved?
|
|
171
|
+
rescue Beaneater::NotFoundError, Beaneater::JobNotReserved
|
|
172
|
+
nil # gone, or no longer reserved by us by the time bury ran
|
|
173
|
+
end
|
|
136
174
|
end # Jobs
|
|
137
175
|
end # Beaneater
|
data/lib/beaneater/job/record.rb
CHANGED
|
@@ -38,8 +38,8 @@ class Beaneater
|
|
|
38
38
|
#
|
|
39
39
|
# @api public
|
|
40
40
|
def bury(options={})
|
|
41
|
-
|
|
42
|
-
with_reserved("bury #{
|
|
41
|
+
pri = Arguments.unsigned(options.fetch(:pri) { stats.pri }, 'pri')
|
|
42
|
+
with_reserved("bury #{command_id} #{pri}") do
|
|
43
43
|
@reserved = false
|
|
44
44
|
end
|
|
45
45
|
end
|
|
@@ -56,8 +56,10 @@ class Beaneater
|
|
|
56
56
|
#
|
|
57
57
|
# @api public
|
|
58
58
|
def release(options={})
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
job_stats = stats unless options.key?(:pri) && options.key?(:delay) # one stats-job for both defaults
|
|
60
|
+
pri = Arguments.unsigned(options.fetch(:pri) { job_stats.pri }, 'pri')
|
|
61
|
+
delay = Arguments.unsigned(options.fetch(:delay) { job_stats.delay }, 'delay')
|
|
62
|
+
with_reserved("release #{command_id} #{pri} #{delay}") do
|
|
61
63
|
@reserved = false
|
|
62
64
|
end
|
|
63
65
|
end
|
|
@@ -71,7 +73,7 @@ class Beaneater
|
|
|
71
73
|
#
|
|
72
74
|
# @api public
|
|
73
75
|
def touch
|
|
74
|
-
with_reserved("touch #{
|
|
76
|
+
with_reserved("touch #{command_id}")
|
|
75
77
|
end
|
|
76
78
|
|
|
77
79
|
# Sends command to delete a job.
|
|
@@ -83,7 +85,7 @@ class Beaneater
|
|
|
83
85
|
#
|
|
84
86
|
# @api public
|
|
85
87
|
def delete
|
|
86
|
-
transmit("delete #{
|
|
88
|
+
transmit("delete #{command_id}") { @reserved = false }
|
|
87
89
|
end
|
|
88
90
|
|
|
89
91
|
# Sends command to kick a buried job.
|
|
@@ -95,7 +97,7 @@ class Beaneater
|
|
|
95
97
|
#
|
|
96
98
|
# @api public
|
|
97
99
|
def kick
|
|
98
|
-
transmit("kick-job #{
|
|
100
|
+
transmit("kick-job #{command_id}")
|
|
99
101
|
end
|
|
100
102
|
|
|
101
103
|
# Sends command to get stats about job.
|
|
@@ -107,7 +109,7 @@ class Beaneater
|
|
|
107
109
|
#
|
|
108
110
|
# @api public
|
|
109
111
|
def stats
|
|
110
|
-
res = transmit("stats-job #{
|
|
112
|
+
res = transmit("stats-job #{command_id}")
|
|
111
113
|
StatStruct.from_hash(res[:body])
|
|
112
114
|
end
|
|
113
115
|
|
|
@@ -195,6 +197,13 @@ class Beaneater
|
|
|
195
197
|
|
|
196
198
|
protected
|
|
197
199
|
|
|
200
|
+
# The job's id, checked before it is written into a command.
|
|
201
|
+
#
|
|
202
|
+
# @raise [ArgumentError] The id is not a whole number.
|
|
203
|
+
def command_id
|
|
204
|
+
Arguments.integer(id, 'job id')
|
|
205
|
+
end
|
|
206
|
+
|
|
198
207
|
# Transmit command to beanstalkd instance and fetch response.
|
|
199
208
|
#
|
|
200
209
|
# @param [String] cmd Beanstalkd command to send.
|
|
@@ -50,6 +50,13 @@ class Beaneater
|
|
|
50
50
|
end
|
|
51
51
|
end
|
|
52
52
|
|
|
53
|
+
# Answers true for the keys the hash holds (string or symbol), as OpenStruct does for its
|
|
54
|
+
# members; method_missing reads and writes those.
|
|
55
|
+
def respond_to_missing?(method_name_sym, include_private = false)
|
|
56
|
+
name = method_name_sym.to_s.chomp("=")
|
|
57
|
+
@hash.key?(name) || @hash.key?(name.to_sym) || super
|
|
58
|
+
end
|
|
59
|
+
|
|
53
60
|
def __new_ostruct_member__(method_name_sym)
|
|
54
61
|
self.class.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
|
|
55
62
|
def #{ method_name_sym }
|