beaneater 1.2.0 → 1.3.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7397bf5f83a1ba3ff93d90fb1ee7718d8dcaf90ac45ecdedd236fe4fe666c5eb
4
- data.tar.gz: e3f0776719d39a2eb235a921b505bddb3af25be0c915718be3b24a46dd0afd0b
3
+ metadata.gz: 69fc39a3d9d9dc68b793a7b82db8ccac3226c1729c163a966016f49ddd85607a
4
+ data.tar.gz: 7112d6b2669da5a2971bee248e9321cb3717d1023289b5ec7bba0bdcdf37a12e
5
5
  SHA512:
6
- metadata.gz: 9e6b026dbb985f693b2fb0c494084223f86100850210cef83af8d6c7a951e6f81b2dd620262d5f28fa4a18ec8c26542409c45fd9404199dba766470af8265af1
7
- data.tar.gz: a73f631654a1147afcaed139b24b8ec1748fde51b02ff9e84492e8ccdcae81cc84177951b5faebf5d8c06189188b7448e21c346f2b2650219467bcbe1f62b1c8
6
+ metadata.gz: 5669fb49b06d4714edbb3285991a8f184d7505681abc395f9bad064a9ed4984b1be06d64e76b002f88858916321ab6bc9885114cea9fe54e79151ab4a8f6b98c
7
+ data.tar.gz: 0ac491e1e6b02dbbc0a15c7b89439cbaa15f7cf191f39896336b87b02505a8414713063fdb752c885eed1dea4a6a823a5b160f11e509f2d999f132426ccf4cb7
@@ -29,7 +29,9 @@ jobs:
29
29
  - name: Download & Extract beanstalkd
30
30
  run: curl -L https://github.com/beanstalkd/beanstalkd/archive/refs/tags/v1.13.tar.gz | tar xz
31
31
  - name: Make beanstalkd
32
- run: make
32
+ # beanstalkd 1.13 builds with -Werror and predates C23, which newer compilers default to: build it
33
+ # as C17, and keep the const pointer newer C libraries' memchr() returns to prot.c a warning
34
+ run: make CFLAGS='-std=gnu17 -Wno-error=discarded-qualifiers'
33
35
  working-directory: beanstalkd-1.13
34
36
  - name: Set up Ruby
35
37
  uses: ruby/setup-ruby@v1
data/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # CHANGELOG for Beaneater
2
2
 
3
+ ## 1.3.1 (November 4 2026)
4
+
5
+ * `jobs.process!` no longer checks with the server on a job it has just deleted, or released for another try, before moving on (the check sent `stats-job` and could never bury the job): a job whose handler finishes now takes 3 commands (`reserve`, `stats-job`, `delete`) instead of 4, and a retried job takes 2 fewer. A job whose handler raised and that isn't released is still buried as before (@nesquena)
6
+ * `client.stats`, `tube.stats` and `job.stats` parse the server's reply with less work, so polling stats takes noticeably less CPU; the results are unchanged (@nesquena)
7
+
8
+ ## 1.3.0 (November 1 2026)
9
+
10
+ * Check tube names, job ids and numbers before writing them into a command. A tube name beanstalkd does not accept (up to 200 letters, digits and `-+/;.$_()`, not starting with a hyphen) raises `InvalidTubeName` from every tube command (`use`, `watch`, `ignore`, `put`, `peek`, `kick`, `stats`, `pause`, and restoring the watched tubes on reconnect); names such as `demo.test.foo`, `jobs(eu).mailers` and `MyApp.mailers` stay valid. `watch`'s `InvalidTubeName` message now reads "Tube cannot be named '<name>'", as `use`'s does, and `tubes.watch(:t)` and `tubes.ignore(:t)` return the names as Strings. A job id that is not a whole number (an Integer or a String of digits), a priority, delay, TTR or pause delay that is not a whole number from 0 to 4294967295 (the range beanstalkd reads), a reserve timeout or kick count that is neither a whole number nor a Float, and a peek state other than `ready`, `delayed` or `buried` raise `ArgumentError`. Such values used to be sent as given and fail on the server with `BadFormatError` or `UnknownCommandError`, or be misread. What to do: `tube.stats`, `tube.pause` and `tubes.ignore` with such a tube name now raise `InvalidTubeName` instead of `BadFormatError`, and the values above raise `ArgumentError` (`jobs.find("abc")`, `tube.put(body, :ttr => 1.5)`, `tube.peek(:reserved)`) instead of `BadFormatError` or `UnknownCommandError`, both `Beaneater::UnexpectedResponse`s; code that rescues `Beaneater::UnexpectedResponse` around these calls should also rescue `Beaneater::InvalidTubeName` and `ArgumentError` (@nesquena)
11
+ * `stats[key]` (on `client.stats`, `job.stats` and `tube.stats`) reads the stat named by key; a key that is not a stat returns nil (keys that are also method names, such as `"hash"` or `"send"`, used to return something else or raise `ArgumentError`). Readers such as `stats.current_jobs_ready` and hyphenated keys such as `stats['current-jobs-ready']` work as before (@nesquena)
12
+ * Development only: require redcarpet 3.6 for the YARD docs task (`rake yard`), which failed with redcarpet 1.x (`undefined method 'lax_spacing=' for RedcarpetCompat`); this also clears the Dependabot alert on redcarpet 1.x. The gem itself has no new dependency (@nesquena)
13
+ * Set the gem's homepage (it was empty) and add `changelog_uri`, `source_code_uri` and `bug_tracker_uri` to its metadata, so rubygems.org links to the repository, this changelog and the issues; set `rubygems_mfa_required`, so pushing a release to rubygems.org now requires MFA; remove the unused `.travis.yml` (@nesquena)
14
+ * `NotConnected` for an address beaneater can't parse (`[::1]:11300`, `::1`, `beanstalk://host:11300`) names the address as given, leaving out any `user:password@`; the message read "Connection to beanstalk ':' is closed!". IPv6 addresses and URLs are still not supported (@nesquena)
15
+ * `jobs.process!` with no processor registered raises `ArgumentError` ("no processors registered: call jobs.register(tube_name) { |job| ... } first") instead of `NoMethodError: undefined method 'keys' for nil`; it sends nothing to the server (@nesquena)
16
+ * `respond_to?` on `client.stats` and on a `StatStruct` (`job.stats`, `tube.stats`) answers true for every stats key, also before the key is first read (it was false until then), so `respond_to?` and `method(:key)` agree with the readers. `client.stats.respond_to?` asks the server for the keys, as reading a stat does (@nesquena)
17
+ * The connection remembers each watched tube once and by name, so a reconnect no longer re-sends `watch` for every repeated `tubes.watch(name)`, and `tubes.ignore(:name)` forgets a tube watched as `"name"` (and the other way round); `connection.tubes_watched` holds only strings (@nesquena)
18
+ * `Job#release` and `Job#bury` no longer send `stats-job` for a `:pri` or `:delay` the caller gave: `release(:pri => p, :delay => d)` and `bury(:pri => p)` now take no extra round trip (they took 2 and 1), and `release` with either one missing takes one (it took 2) (@nesquena)
19
+
3
20
  ## 1.2.0 (October 31 2026)
4
21
 
5
22
  * `Jobs#process!` buries a job whose body the `job_parser` rejects (`JSON.parse` on a non-JSON job, say); it used to stay reserved until its TTR ran out and then fail again, for ever. A parser that raises `AbortProcessingError` has its job buried and stops the loop, as a handler's abort does. The job is not buried when the parser raises `NotConnected` while this client's connection is gone (`process!` raises it, and beanstalkd releases the job), an exception that isn't a `StandardError` (`process!` raises it, and the job stays reserved until its TTR runs out or the connection closes), or one that can't be copied (raised untagged, so `process!` can't tell which job it came from: the job stays reserved and `process!` keeps failing on it; make parser exceptions copyable). A plain `tubes.reserve` raises a copy of the parser's error with the same class, message, cause and backtrace (a frozen exception, for which Ruby records no backtrace, gets one that starts in beaneater), so `rescue JSON::ParserError` keeps working; the copy is also a `Beaneater::JobParseFailure`, whose `#job_id` names the job, still reserved by the connection (@nesquena)
data/Gemfile CHANGED
@@ -6,7 +6,7 @@ source 'https://rubygems.org'
6
6
  gemspec
7
7
 
8
8
  group :development do
9
- gem 'redcarpet', '~> 1'
9
+ gem 'redcarpet', '~> 3.6'
10
10
  gem 'github-markup'
11
11
  gem 'yard'
12
12
  end
data/README.md CHANGED
@@ -448,12 +448,17 @@ are listed below:
448
448
  | Errors | Description |
449
449
  | -------------------- | ------------- |
450
450
  | Beaneater::NotConnected | Client connection to beanstalk cannot be established. |
451
- | Beaneater::InvalidTubeName | Specified tube name for use or watch is not valid. |
451
+ | Beaneater::InvalidTubeName | Specified tube name is not valid: beanstalkd takes up to 200 letters, digits and `-+/;.$_()`, not starting with a hyphen. |
452
452
  | Beaneater::NotFoundError | Specified job or tube could not be found. |
453
453
  | Beaneater::TimedOutError | Job could not be reserved within time specified. |
454
454
  | Beaneater::SocketTimeout | No reply within `read_timeout` (or the write exceeded `write_timeout`); the connection is dropped and the next command reconnects. A subclass of `NotConnected`, not to be confused with `TimedOutError`. |
455
455
  | Beaneater::JobNotReserved | Job has not been reserved and action cannot be taken. |
456
456
 
457
+ A job id that is not a whole number (an Integer or a String of digits), a priority, delay, TTR or
458
+ pause delay that is not a whole number from 0 to 4294967295, a reserve timeout or kick count that is
459
+ neither a whole number nor a Float, and a peek state other than `ready`, `delayed` or `buried` raise
460
+ `ArgumentError` before anything is sent.
461
+
457
462
  There are other exceptions that are less common such as `OutOfMemoryError`, `DrainingError`,
458
463
  `DeadlineSoonError`, `InternalError`, `BadFormatError`, `UnknownCommandError`,
459
464
  `ExpectedCRLFError`, `JobTooBigError`, `NotIgnoredError`. Be sure to check the
data/Rakefile CHANGED
@@ -4,6 +4,9 @@ require "bundler/gem_tasks"
4
4
  require 'rake/testtask'
5
5
  require 'yard'
6
6
  require 'redcarpet'
7
+ require 'json'
8
+ require 'net/http'
9
+ require_relative 'lib/beaneater/version'
7
10
 
8
11
  # rake test
9
12
  Rake::TestTask.new do |t|
@@ -32,4 +35,106 @@ YARD::Rake::YardocTask.new do |t|
32
35
  t.options = []
33
36
  end
34
37
 
38
+ # rake release:check (rake release runs it first, before it builds, tags or pushes):
39
+ # HEAD must be on master (or X.Y-stable), committed and at the remote branch it will be
40
+ # pushed to (`origin` unless `rake release[remote]` or the branch's upstream says
41
+ # otherwise), version.rb must match the top CHANGELOG.md heading, stamped with a date,
42
+ # and neither the tag nor the gem version may exist yet.
43
+ desc "Check that HEAD can be released as beaneater #{Beaneater::VERSION}"
44
+ task "release:check", [:remote] do |_, args|
45
+ version = Beaneater::VERSION
46
+ tag = "v#{version}"
47
+ git = ->(*a) { out = IO.popen(["git", *a], err: File::NULL, &:read); out.strip if $?.success? }
48
+ errors = []
49
+
50
+ branch = git.("rev-parse", "--abbrev-ref", "HEAD").to_s
51
+ remote = args[:remote] || git.("config", "--get", "branch.#{branch}.remote") || "origin"
52
+ errors << "git fetch #{remote} failed" unless system("git", "fetch", "--quiet", remote)
53
+ stable = "#{version[/\A\d+\.\d+/]}-stable"
54
+ errors << "on #{branch}, not master or #{stable}" unless ["master", stable].include?(branch)
55
+ errors << "there are uncommitted changes" unless git.("status", "--porcelain") == ""
56
+ head = git.("rev-parse", "HEAD")
57
+ unless head && head == git.("rev-parse", "--verify", "--quiet", "refs/remotes/#{remote}/#{branch}")
58
+ errors << "#{branch} is not at #{remote}/#{branch} (push or pull first; release a merged commit)"
59
+ end
60
+
61
+ heading = File.foreach(File.expand_path('CHANGELOG.md', __dir__), encoding: "bom|utf-8").find { |l| l.start_with?("## ") }.to_s.strip
62
+ top, rest = heading.match(/\A## (\d+\.\d+\.\d+)( .*|)\z/)&.captures
63
+ if top != version
64
+ errors << "CHANGELOG.md starts with '#{heading}', not #{version}"
65
+ elsif rest !~ /\b(19|20)\d\d\b/ || rest =~ /\b(unreleased|tbd|tba)\b/i
66
+ errors << "CHANGELOG.md's '#{heading}' isn't stamped with a date"
67
+ end
68
+
69
+ local_tag = git.("tag", "--list", tag)
70
+ remote_tag = git.("ls-remote", "--tags", remote, "refs/tags/#{tag}")
71
+ if local_tag.nil? || remote_tag.nil?
72
+ errors << "couldn't check for tag #{tag}"
73
+ elsif !(local_tag.empty? && remote_tag.empty?)
74
+ page = args[:remote] ? "rake 'release:github[#{args[:remote]}]'" : "rake release:github"
75
+ errors << "tag #{tag} already exists (if only the gem push failed: gem push pkg/beaneater-#{version}.gem, then #{page})"
76
+ end
77
+
78
+ begin
79
+ published = JSON.parse(Net::HTTP.get(URI("https://rubygems.org/api/v1/versions/beaneater.json")))
80
+ errors << "beaneater #{version} is already on rubygems.org" if published.any? { |v| v["number"] == version }
81
+ rescue StandardError => e
82
+ errors << "couldn't check rubygems.org (#{e.message})"
83
+ end
84
+
85
+ abort "Not ready to release #{version}:\n#{errors.map { |e| " - #{e}" }.join("\n")}" unless errors.empty?
86
+ puts "Ready to release beaneater #{version} (#{git.("rev-parse", "--short", "HEAD")} on #{branch}, #{remote})"
87
+ end
88
+ Rake::Task["release"].prerequisites.unshift("release:check")
89
+ %w[release:source_control_push release:rubygem_push].each { |t| Rake::Task[t].enhance(["release:check"]) }
90
+
91
+ # rake release:github (rake release runs it last, once the tag and the gem are pushed):
92
+ # creates the GitHub release page for the tag through the gh CLI, on the github.com
93
+ # repository the remote pushes to, with a link to the CHANGELOG and GitHub's generated
94
+ # notes since the previous version's tag. It is marked Latest only when no higher version
95
+ # is tagged, so a release from an X.Y-stable branch doesn't take that from a newer one.
96
+ # If the page already exists it does nothing, so it can also be run by hand to finish a release.
97
+ desc "Create the GitHub release page for v#{Beaneater::VERSION}"
98
+ task "release:github", [:remote] do |_, args|
99
+ version = Gem::Version.new(Beaneater::VERSION)
100
+ tag = "v#{version}"
101
+ git = ->(*a) { out = IO.popen(["git", *a], err: File::NULL, &:read); out.strip if $?.success? }
102
+ branch = git.("rev-parse", "--abbrev-ref", "HEAD").to_s
103
+ remote = args[:remote] || git.("config", "--get", "branch.#{branch}.remote") || "origin"
104
+ url = git.("remote", "get-url", "--push", remote).to_s.split("\n").first.to_s
105
+ repo = url[%r{(?:\A|[@/.])github\.com[:/]([^/]+/[^/]+?)(?:\.git)?/?\z}i, 1] or abort "#{remote} isn't a GitHub repository"
106
+ # the push URL's tags, not the fetch URL's: the page goes to the repository the tag was pushed to
107
+ tags = git.("ls-remote", "--tags", url, "refs/tags/v*") or abort "Couldn't list the tags on #{remote}"
108
+ tagged = tags.split("\n").filter_map { |l| l[%r{\trefs/tags/v(\d+\.\d+\.\d+)\z}, 1] }.map { |v| Gem::Version.new(v) }
109
+ previous = tagged.select { |v| v < version }.max
110
+ options = ["--latest=#{tagged.none? { |v| v > version }}"]
111
+ options += ["--notes-start-tag", "v#{previous}"] if previous
112
+ # gh adds the generated notes after a single newline; the second one keeps them out of this paragraph
113
+ notes = "See [CHANGELOG.md](https://github.com/#{repo}/blob/#{tag}/CHANGELOG.md) for what changed, and what to do when upgrading.\n"
114
+ gh_repo = "github.com/#{repo}" # so an exported GH_HOST doesn't send it elsewhere
115
+
116
+ if system("gh", "release", "view", tag, "-R", gh_repo, out: File::NULL, err: File::NULL)
117
+ puts "GitHub release #{tag} already exists on #{repo}"
118
+ elsif system("gh", "release", "create", tag, "-R", gh_repo, "--verify-tag", "--title", tag, *options,
119
+ "--generate-notes", "--notes", notes)
120
+ puts "Created GitHub release #{tag} on #{repo}"
121
+ else
122
+ abort "Couldn't create GitHub release #{tag} on #{repo} (is gh installed and signed in?)"
123
+ end
124
+ end
125
+ # The gem is out by then, so a failure here only warns and says how to finish.
126
+ Rake::Task["release"].enhance do |_, args|
127
+ if %w[n no nil false off 0].include?(ENV["gem_push"].to_s.downcase)
128
+ puts "gem_push is off, so no GitHub release page"
129
+ next
130
+ end
131
+ begin
132
+ Rake::Task["release:github"].invoke(args[:remote])
133
+ rescue SystemExit, StandardError => e
134
+ warn "#{e.class}: #{e.message} (#{e.backtrace&.first})" unless e.is_a?(SystemExit)
135
+ page = args[:remote] ? "rake 'release:github[#{args[:remote]}]'" : "rake release:github"
136
+ warn "The tag and the gem are pushed; only the GitHub release page is missing. Run: #{page}"
137
+ end
138
+ end
139
+
35
140
  task :default => 'test:full'
data/beaneater.gemspec CHANGED
@@ -11,8 +11,14 @@ Gem::Specification.new do |gem|
11
11
  gem.email = ["nico.taing@gmail.com"]
12
12
  gem.description = %q{Simple beanstalkd client for ruby}
13
13
  gem.summary = %q{Simple beanstalkd client for ruby.}
14
- gem.homepage = ""
14
+ gem.homepage = "https://github.com/beanstalkd/beaneater"
15
15
  gem.license = 'MIT'
16
+ gem.metadata = {
17
+ "changelog_uri" => "https://github.com/beanstalkd/beaneater/blob/master/CHANGELOG.md",
18
+ "source_code_uri" => "https://github.com/beanstalkd/beaneater",
19
+ "bug_tracker_uri" => "https://github.com/beanstalkd/beaneater/issues",
20
+ "rubygems_mfa_required" => "true"
21
+ }
16
22
 
17
23
  gem.files = `git ls-files`.split($/)
18
24
  gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Beaneater
4
+ # Checks the values beaneater writes into a command line, so that each one stays a single
5
+ # argument of the form beanstalkd accepts.
6
+ #
7
+ # @private
8
+ module Arguments
9
+ # beanstalkd's tube names: 1 to 200 of these characters, not starting with a hyphen
10
+ TUBE_NAME = %r{\A[A-Za-z0-9+/;.$_()][A-Za-z0-9\-+/;.$_()]{0,199}\z}
11
+ # A whole number, as an Integer or a String of digits
12
+ INTEGER = /\A-?\d+\z/
13
+ # One that isn't negative
14
+ UNSIGNED = /\A\d+\z/
15
+ # The largest priority, delay or TTR beanstalkd reads (a 32-bit unsigned number)
16
+ UINT32_MAX = 4_294_967_295
17
+ # The job states a tube can be peeked at
18
+ PEEK_STATES = %w(ready delayed buried).freeze
19
+
20
+ module_function
21
+
22
+ # @return [String] the tube name
23
+ # @raise [Beaneater::InvalidTubeName] name isn't a tube name beanstalkd accepts
24
+ def tube_name(name)
25
+ name = name.to_s
26
+ raise InvalidTubeName, "Tube cannot be named '#{name}'" unless name.valid_encoding? && name.match?(TUBE_NAME)
27
+ name
28
+ end
29
+
30
+ # @return [Integer, String] value, an Integer or a String of digits (a job id, a priority, a delay)
31
+ # @raise [ArgumentError] value is anything else
32
+ def integer(value, what)
33
+ return value if integer?(value)
34
+ raise ArgumentError, "#{what} must be an integer, not #{value.inspect}"
35
+ end
36
+
37
+ # Like {.integer}, for values beanstalkd takes only as a whole number from 0 to {UINT32_MAX} (a
38
+ # priority, a delay, a TTR): any other would fail on the server, and for put only after its body is sent.
39
+ # @return [Integer, String] value
40
+ # @raise [ArgumentError] value is anything else
41
+ def unsigned(value, what)
42
+ number = value.is_a?(String) && value.match?(UNSIGNED) ? Integer(value, 10) : value
43
+ return value if number.is_a?(Integer) && number >= 0 && number <= UINT32_MAX
44
+ raise ArgumentError, "#{what} must be a whole number from 0 to #{UINT32_MAX}, not #{value.inspect}"
45
+ end
46
+
47
+ # Like {.integer}, also accepting a Float, which beanstalkd reads up to the decimal point
48
+ # where a command allows it (a reserve timeout, the number of jobs to kick).
49
+ def number(value, what)
50
+ return value if value.is_a?(Float) || integer?(value)
51
+ raise ArgumentError, "#{what} must be a number, not #{value.inspect}"
52
+ end
53
+
54
+ def integer?(value)
55
+ value.is_a?(Integer) || (value.is_a?(String) && value.match?(INTEGER))
56
+ end
57
+
58
+ # @return [String] the job state to peek at
59
+ # @raise [ArgumentError] state isn't ready, delayed or buried
60
+ def peek_state(state)
61
+ state = state.to_s
62
+ return state if PEEK_STATES.include?(state)
63
+ raise ArgumentError, "state must be one of #{PEEK_STATES.join(', ')}, not #{state.inspect}"
64
+ end
65
+ end # Arguments
66
+ end # Beaneater
@@ -152,13 +152,15 @@ class Beaneater
152
152
  end
153
153
  alias :inspect :to_s
154
154
 
155
+ # The watched tubes are kept by name, once each: a reconnect watches them again.
155
156
  def add_to_watched(tube_name)
156
- @tubes_watched << tube_name
157
- @tubes_watched.uniq
157
+ @tubes_watched << tube_name.to_s
158
+ @tubes_watched.uniq!
159
+ @tubes_watched
158
160
  end
159
161
 
160
162
  def remove_from_watched(tube_name)
161
- @tubes_watched.delete(tube_name)
163
+ @tubes_watched.delete(tube_name.to_s)
162
164
  end
163
165
 
164
166
  protected
@@ -323,13 +325,13 @@ class Beaneater
323
325
  def _initialize_tubes
324
326
  if @tubes_watched != ['default']
325
327
  tubes_watched.each do |t|
326
- _exchange("watch #{t}")
328
+ _exchange("watch #{Arguments.tube_name(t)}")
327
329
  end
328
330
 
329
331
  _exchange("ignore default") unless tubes_watched.include?('default')
330
332
  end
331
333
 
332
- _exchange("use #{tube_used}") if @tube_used != 'default'
334
+ _exchange("use #{Arguments.tube_name(tube_used)}") if @tube_used != 'default'
333
335
  end
334
336
 
335
337
  # One attempt at a command, made holding the lock: reconnect (and restore the tubes) if the
@@ -412,9 +414,9 @@ class Beaneater
412
414
  value[1..-2]
413
415
  elsif text
414
416
  value
415
- elsif value =~ /\A-?\d+\z/
417
+ elsif value.match?(/\A-?\d+\z/)
416
418
  value.to_i
417
- elsif value =~ /\A-?\d+\.\d+\z/
419
+ elsif value.match?(/\A-?\d+\.\d+\z/)
418
420
  value.to_f
419
421
  elsif value == 'true' || value == 'false'
420
422
  value == 'true'
@@ -500,7 +502,10 @@ class Beaneater
500
502
  # Raises an error to be triggered when the connection has failed
501
503
  # @raise [Beaneater::NotConnected] Beanstalkd is no longer connected
502
504
  def _raise_not_connected!
503
- raise Beaneater::NotConnected, "Connection to beanstalk '#{@host}:#{@port}' is closed!"
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!"
504
509
  end
505
510
 
506
511
  end # Connection
@@ -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,9 +103,11 @@ 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)
@@ -129,9 +131,11 @@ class Beaneater
129
131
  begin
130
132
  processor[:block].call(@current_job)
131
133
  @current_job.delete
134
+ @current_job = nil # deleted, so there is nothing for the ensure below to bury
132
135
  rescue *processor[:retry_on]
133
136
  if @current_job.stats.releases < processor[:max_retries]
134
137
  @current_job.release(:delay => release_delay)
138
+ @current_job = nil # released for another try, so no longer ours to bury
135
139
  end
136
140
  end
137
141
  rescue AbortProcessingError
@@ -38,8 +38,8 @@ class Beaneater
38
38
  #
39
39
  # @api public
40
40
  def bury(options={})
41
- options = { :pri => stats.pri }.merge(options)
42
- with_reserved("bury #{id} #{options[:pri]}") do
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
- options = { :pri => stats.pri, :delay => stats.delay }.merge(options)
60
- with_reserved("release #{id} #{options[:pri]} #{options[:delay]}") do
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 #{id}")
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 #{id}") { @reserved = false }
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 #{id}")
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 #{id}")
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 }
@@ -13,24 +13,34 @@ class Beaneater
13
13
  #
14
14
  def self.from_hash(hash)
15
15
  return unless hash.is_a?(Hash)
16
- underscore_hash = hash.inject({}) { |r, (k, v)| r[k.to_s.gsub(/-/, '_')] = v; r }
16
+ underscore_hash = hash.inject({}) { |r, (k, v)| r[underscore(k)] = v; r }
17
17
  self.new(underscore_hash)
18
18
  end
19
19
 
20
+ # The key as a String with its hyphens turned into underscores, with String#tr for speed. A key
21
+ # in an encoding that isn't ASCII-compatible (UTF-16, say) takes gsub, so that the
22
+ # Encoding::CompatibilityError it raises keeps gsub's message.
23
+ def self.underscore(key)
24
+ key = key.to_s
25
+ key.encoding.ascii_compatible? ? key.tr('-', '_') : key.gsub(/-/, '_')
26
+ end
27
+ private_class_method :underscore
28
+
20
29
  # Access value for stat with specified key.
21
30
  #
22
31
  # Keys are stored underscored (see {.from_hash}), so hyphenated beanstalkd
23
- # names like "current-jobs-ready" are underscored before lookup. This also
24
- # avoids defining an invalid, hyphenated method name via method_missing.
32
+ # names like "current-jobs-ready" are underscored before lookup. The value
33
+ # is read from the stats themselves, as the readers do, so any key works.
25
34
  #
26
35
  # @param [String] key Key to fetch from stats.
27
- # @return [String, Integer] Value for specified stat key.
36
+ # @return [String, Integer, nil] Value for specified stat key, nil if there is none.
28
37
  # @example
29
38
  # @stats['foo'] # => "bar"
30
39
  # @stats['current-jobs-ready'] # => 5
31
40
  #
32
41
  def [](key)
33
- self.send(key.to_s.gsub(/-/, '_'))
42
+ name = self.class.send(:underscore, key)
43
+ @hash.fetch(name) { @hash[name.to_sym] }
34
44
  end
35
45
 
36
46
  # Returns set of keys within this struct
@@ -65,6 +65,12 @@ class Beaneater
65
65
  end
66
66
  end
67
67
 
68
+ # Answers true for the stats keys method_missing looks up.
69
+ # @api public
70
+ def respond_to_missing?(name, include_private = false)
71
+ data.keys.include?(name.to_s) || super
72
+ end
73
+
68
74
  protected
69
75
 
70
76
  # Returns struct based on stats data from response.
@@ -63,7 +63,7 @@ class Beaneater
63
63
  # @api public
64
64
  def reserve(timeout=nil, &block)
65
65
  res = transmit(
66
- timeout ? "reserve-with-timeout #{timeout}" : 'reserve')
66
+ timeout ? "reserve-with-timeout #{Arguments.number(timeout, 'timeout')}" : 'reserve')
67
67
  job = Job.new(client, res)
68
68
  block.call(job) if block_given?
69
69
  job
@@ -132,7 +132,7 @@ class Beaneater
132
132
  #
133
133
  # @api public
134
134
  def watch(*names)
135
- names.each do |t|
135
+ names.map { |t| Arguments.tube_name(t) }.each do |t|
136
136
  transmit "watch #{t}"
137
137
  client.connection.add_to_watched(t)
138
138
  end
@@ -162,7 +162,7 @@ class Beaneater
162
162
  #
163
163
  # @api public
164
164
  def ignore(*names)
165
- names.each do |w|
165
+ names.map { |w| Arguments.tube_name(w) }.each do |w|
166
166
  transmit "ignore #{w}"
167
167
  client.connection.remove_from_watched(w)
168
168
  end
@@ -175,9 +175,11 @@ class Beaneater
175
175
  # @conn.tubes.use("some-tube")
176
176
  #
177
177
  def use(tube)
178
- return tube if last_used == tube
179
- transmit("use #{tube}")
180
- self.last_used = tube
178
+ name = Arguments.tube_name(tube)
179
+ return tube if last_used == name
180
+ transmit("use #{name}")
181
+ self.last_used = name
182
+ tube
181
183
  rescue BadFormatError
182
184
  raise InvalidTubeName, "Tube cannot be named '#{tube}'"
183
185
  end
@@ -52,7 +52,8 @@ class Beaneater
52
52
  :ttr => config.default_put_ttr
53
53
  }.merge(options)
54
54
 
55
- cmd_options = "#{options[:pri]} #{options[:delay]} #{options[:ttr]} #{serialized_body.bytesize}"
55
+ pri, delay, ttr = %i(pri delay ttr).map { |key| Arguments.unsigned(options[key], key.to_s) }
56
+ cmd_options = "#{pri} #{delay} #{ttr} #{serialized_body.bytesize}"
56
57
  transmit("put #{cmd_options}\r\n#{serialized_body}")
57
58
  end
58
59
  end
@@ -67,7 +68,7 @@ class Beaneater
67
68
  # @api public
68
69
  def peek(state)
69
70
  safe_use do
70
- res = transmit("peek-#{state}")
71
+ res = transmit("peek-#{Arguments.peek_state(state)}")
71
72
  Job.new(client, res)
72
73
  end
73
74
  rescue Beaneater::NotFoundError
@@ -99,7 +100,7 @@ class Beaneater
99
100
  #
100
101
  # @api public
101
102
  def kick(bounds=1)
102
- safe_use { transmit("kick #{bounds}") }
103
+ safe_use { transmit("kick #{Arguments.number(bounds, 'bounds')}") }
103
104
  end
104
105
 
105
106
  # Returns related stats for this tube.
@@ -110,7 +111,7 @@ class Beaneater
110
111
  #
111
112
  # @api public
112
113
  def stats
113
- res = transmit("stats-tube #{name}")
114
+ res = transmit("stats-tube #{Arguments.tube_name(name)}")
114
115
  StatStruct.from_hash(res[:body])
115
116
  end
116
117
 
@@ -123,7 +124,7 @@ class Beaneater
123
124
  #
124
125
  # @api public
125
126
  def pause(delay)
126
- transmit("pause-tube #{name} #{delay}")
127
+ transmit("pause-tube #{Arguments.tube_name(name)} #{Arguments.unsigned(delay, 'delay')}")
127
128
  end
128
129
 
129
130
  # Clears all unreserved jobs in all states from the tube
@@ -2,5 +2,5 @@
2
2
 
3
3
  class Beaneater
4
4
  # Current version of gem.
5
- VERSION = "1.2.0"
5
+ VERSION = "1.3.1"
6
6
  end
data/lib/beaneater.rb CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  require 'thread' unless defined?(Mutex)
4
4
 
5
- %w(version configuration errors connection tube job stats).each do |f|
5
+ %w(version configuration errors arguments connection tube job stats).each do |f|
6
6
  require "beaneater/#{f}"
7
7
  end
8
8
 
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ # test/arguments_test.rb
4
+
5
+ require File.expand_path('../test_helper', __FILE__)
6
+
7
+ describe "Command arguments" do
8
+ before do
9
+ @beanstalk = Beaneater.new('localhost')
10
+ end
11
+
12
+ # The connection's next command still gets its own reply
13
+ def assert_in_step
14
+ assert_equal 'USING', @beanstalk.connection.transmit('list-tube-used')[:status]
15
+ end
16
+
17
+ describe "tube names" do
18
+ it "should raise InvalidTubeName for a name beanstalkd does not accept" do
19
+ calls = {
20
+ 'use' => ->(name) { @beanstalk.tubes.use(name) },
21
+ 'watch' => ->(name) { @beanstalk.tubes.watch(name) },
22
+ 'ignore' => ->(name) { @beanstalk.tubes.ignore(name) },
23
+ 'put' => ->(name) { @beanstalk.tubes.find(name).put('x') },
24
+ 'peek' => ->(name) { @beanstalk.tubes.find(name).peek(:ready) },
25
+ 'stats' => ->(name) { @beanstalk.tubes.find(name).stats },
26
+ 'pause' => ->(name) { @beanstalk.tubes.find(name).pause(0) }
27
+ }
28
+ ["a\r\nb", "a\nb", "a\rb", "a b", "-a", "a" * 201, "", "tubeé", "a\xffb", "a\xffb".b].each do |name|
29
+ calls.each do |call, block|
30
+ assert_raises(Beaneater::InvalidTubeName, "#{call} #{name.inspect}") { block.call(name) }
31
+ assert_in_step
32
+ end
33
+ end
34
+ assert_equal ['default'], @beanstalk.tubes.watched.map(&:name)
35
+ assert_equal 'default', @beanstalk.tubes.used.name
36
+ end
37
+
38
+ it "should raise InvalidTubeName when a reconnect would restore a name beanstalkd does not accept" do
39
+ @beanstalk.connection.tubes_watched = ['default', "a\r\nb"]
40
+ @beanstalk.connection.connection.shutdown(Socket::SHUT_RDWR) # the next command reconnects
41
+ assert_raises(Beaneater::InvalidTubeName) { @beanstalk.tubes.used }
42
+ @beanstalk.connection.tubes_watched = ['default']
43
+ assert_equal 'default', @beanstalk.tubes.used.name
44
+ end
45
+
46
+ it "should accept every name beanstalkd does" do
47
+ ['demo.test.foo', 'jobs(eu).mailers', 'MyApp.mailers', 'a+b/c;d$e_f-g', 'a' * 200, :symbol_tube].each do |name|
48
+ tube = @beanstalk.tubes.find(name)
49
+ tube.put('job')
50
+ assert_equal name.to_s, tube.stats.name
51
+ tube.pause(0)
52
+ @beanstalk.tubes.watch(name)
53
+ assert_includes @beanstalk.connection.tubes_watched, name.to_s
54
+ assert_equal 'job', tube.peek(:ready).body
55
+ @beanstalk.tubes.ignore(name)
56
+ end
57
+ end
58
+ end # tube names
59
+
60
+ describe "job ids" do
61
+ before do
62
+ @tube = @beanstalk.tubes.find('arguments')
63
+ @id = @tube.put('job')[:id]
64
+ end
65
+
66
+ it "should find a job by an Integer or a String of digits" do
67
+ assert_equal 'job', @beanstalk.jobs.find(@id.to_i).body
68
+ assert_equal 'job', @beanstalk.jobs.find(@id.to_s).body
69
+ end
70
+
71
+ it "should raise ArgumentError for an id that is not a whole number" do
72
+ ["#{@id}\r\nstats", "#{@id}\nstats", "#{@id} 1", "abc", "", nil, 1.5, :"1"].each do |id|
73
+ assert_raises(ArgumentError, id.inspect) { @beanstalk.jobs.find(id) }
74
+ assert_in_step
75
+ job = Beaneater::Job.new(@beanstalk, :id => id, :status => 'RESERVED')
76
+ [:delete, :touch, :kick, :stats, :bury, :release].each do |call|
77
+ assert_raises(ArgumentError, "#{call} #{id.inspect}") { job.send(call) }
78
+ assert_in_step
79
+ end
80
+ end
81
+ assert_equal 'job', @beanstalk.jobs.find(@id).body
82
+ end
83
+ end # job ids
84
+
85
+ describe "numbers" do
86
+ before do
87
+ @tube = @beanstalk.tubes.find('arguments')
88
+ end
89
+
90
+ it "should raise ArgumentError for a number that is not one" do
91
+ ["1\r\nstats", "1\n", "1 2", "x", nil].each do |bad|
92
+ [:pri, :delay, :ttr].each do |key|
93
+ assert_raises(ArgumentError, "put #{key} #{bad.inspect}") { @tube.put('job', key => bad) }
94
+ assert_in_step
95
+ end
96
+ assert_raises(ArgumentError, "pause #{bad.inspect}") { @tube.pause(bad) }
97
+ assert_in_step
98
+ assert_raises(ArgumentError, "kick #{bad.inspect}") { @tube.kick(bad) }
99
+ assert_in_step
100
+ assert_raises(ArgumentError, "reserve #{bad.inspect}") { @beanstalk.tubes.reserve(bad) } if bad
101
+ assert_in_step
102
+
103
+ @tube.put('job')
104
+ job = @tube.reserve(0)
105
+ assert_raises(ArgumentError, "release pri #{bad.inspect}") { job.release(:pri => bad, :delay => 0) }
106
+ assert_in_step
107
+ assert_raises(ArgumentError, "release delay #{bad.inspect}") { job.release(:pri => 1, :delay => bad) }
108
+ assert_in_step
109
+ assert_raises(ArgumentError, "bury pri #{bad.inspect}") { job.bury(:pri => bad) }
110
+ assert_in_step
111
+ job.delete
112
+ end
113
+ assert_nil @tube.peek(:ready)
114
+ end
115
+
116
+ it "should raise ArgumentError for a priority, delay or TTR outside 0 to 4294967295" do
117
+ [-1, "-1", 2**32, "4294967296"].each do |bad|
118
+ [:pri, :delay, :ttr].each do |key|
119
+ assert_raises(ArgumentError, "put #{key} #{bad.inspect}") { @tube.put('stats', key => bad) }
120
+ assert_in_step
121
+ end
122
+ assert_raises(ArgumentError, "pause #{bad.inspect}") { @tube.pause(bad) }
123
+ assert_in_step
124
+
125
+ @tube.put('job')
126
+ job = @tube.reserve(0)
127
+ assert_raises(ArgumentError, "release pri #{bad.inspect}") { job.release(:pri => bad, :delay => 0) }
128
+ assert_in_step
129
+ assert_raises(ArgumentError, "release delay #{bad.inspect}") { job.release(:pri => 1, :delay => bad) }
130
+ assert_in_step
131
+ assert_raises(ArgumentError, "bury pri #{bad.inspect}") { job.bury(:pri => bad) }
132
+ assert_in_step
133
+ job.delete
134
+ end
135
+ assert_nil @tube.peek(:ready)
136
+ end
137
+
138
+ it "should accept the largest priority beanstalkd takes" do
139
+ [4294967295, "4294967295"].each do |pri|
140
+ @tube.put('job', :pri => pri)
141
+ job = @tube.reserve(0)
142
+ assert_equal 4294967295, job.stats.pri
143
+ job.release(:pri => pri, :delay => 0)
144
+ job = @tube.reserve(0)
145
+ job.bury(:pri => pri)
146
+ assert_equal 4294967295, job.stats.pri
147
+ job.delete
148
+ end
149
+ end
150
+
151
+ it "should accept Integers and Strings of digits, and Floats where beanstalkd does" do
152
+ @tube.put('job', :pri => '5', :delay => '0', :ttr => '60')
153
+ job = @tube.reserve(0.5)
154
+ assert_equal 5, job.stats.pri
155
+ job.release(:pri => '6', :delay => '0')
156
+ job = @beanstalk.tubes.reserve('0')
157
+ job.bury(:pri => 7)
158
+ assert_equal 1, @tube.kick(1.5)[:id].to_i
159
+ @tube.pause('0')
160
+ end
161
+ end # numbers
162
+
163
+ describe "peek states" do
164
+ it "should raise ArgumentError for a state other than ready, delayed or buried" do
165
+ tube = @beanstalk.tubes.find('arguments')
166
+ tube.put('job')
167
+ ["ready\r\nstats", "ready ", "reserved", ""].each do |state|
168
+ assert_raises(ArgumentError, state.inspect) { tube.peek(state) }
169
+ assert_in_step
170
+ end
171
+ assert_equal 'job', tube.peek('ready').body
172
+ end
173
+ end # peek states
174
+ end
@@ -30,7 +30,24 @@ describe Beaneater::Connection do
30
30
  end
31
31
 
32
32
  it "should raise on invalid connection" do
33
- assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new("localhost:8544") }
33
+ error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new("localhost:8544") }
34
+ assert_equal "Connection to beanstalk 'localhost:8544' is closed!", error.message
35
+ end
36
+
37
+ it "should leave the user and password out of the address it names" do
38
+ { 'user:secret@127.0.0.1:1' => '127.0.0.1:1',
39
+ 'beanstalk://user:secret@127.0.0.1:11300' => 'beanstalk://127.0.0.1:11300',
40
+ 'user@localhost:8544' => 'localhost:8544' }.each do |address, shown|
41
+ error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new(address) }
42
+ assert_equal "Connection to beanstalk '#{shown}' is closed!", error.message
43
+ end
44
+ end
45
+
46
+ it "should name an address it can't parse as given" do
47
+ ['[::1]:11300', '::1', 'beanstalk://127.0.0.1:11300'].each do |address|
48
+ error = assert_raises(Beaneater::NotConnected) { Beaneater::Connection.new(address) }
49
+ assert_equal "Connection to beanstalk '#{address}' is closed!", error.message
50
+ end
34
51
  end
35
52
 
36
53
  it "should support array connection to single connection" do
data/test/job_test.rb CHANGED
@@ -37,6 +37,14 @@ describe Beaneater::Job do
37
37
  assert_equal "foo bury #{@time}", @tube.peek(:buried).body
38
38
  end
39
39
 
40
+ it "should not look up the job's stats when pri is given" do
41
+ job = @tube.reserve
42
+ job.expects(:stats).never
43
+ job.bury(:pri => 10)
44
+ assert_equal 'buried', @beanstalk.jobs.find(job.id).stats.state
45
+ assert_equal 10, @beanstalk.jobs.find(job.id).stats.pri
46
+ end
47
+
40
48
  it "should not bury if not reserved" do
41
49
  job = @tube.peek(:ready)
42
50
  assert_raises(Beaneater::JobNotReserved) { job.bury }
@@ -76,6 +84,23 @@ describe Beaneater::Job do
76
84
  assert_equal 2, job.stats.delay
77
85
  end
78
86
 
87
+ it "should not look up the job's stats when pri and delay are given" do
88
+ job = @tube.reserve
89
+ job.expects(:stats).never
90
+ job.release :pri => 10, :delay => 2
91
+ job_stats = @beanstalk.jobs.find(job.id).stats
92
+ assert_equal 'delayed', job_stats.state
93
+ assert_equal [10, 2], [job_stats.pri, job_stats.delay]
94
+ end
95
+
96
+ it "should look up the job's stats once for the pri and delay it keeps" do
97
+ job = @tube.reserve
98
+ job.expects(:stats).once.returns(@beanstalk.jobs.find(job.id).stats)
99
+ job.release :delay => 2
100
+ job_stats = @beanstalk.jobs.find(job.id).stats
101
+ assert_equal [5, 2], [job_stats.pri, job_stats.delay]
102
+ end
103
+
79
104
  it "should not released if not reserved" do
80
105
  job = @tube.peek(:ready)
81
106
  assert_raises(Beaneater::JobNotReserved) { job.release }
data/test/jobs_test.rb CHANGED
@@ -58,6 +58,17 @@ describe Beaneater::Jobs do
58
58
  end
59
59
  end # register!
60
60
 
61
+ describe "for process! with no processors" do
62
+ it "should raise ArgumentError without sending a command" do
63
+ client = Beaneater.new('localhost') # not @beanstalk, which the teardown uses
64
+ client.connection.expects(:transmit).never
65
+ error = assert_raises(ArgumentError) { Beaneater::Jobs.new(client).process! }
66
+ assert_match(/register/, error.message)
67
+ ensure
68
+ client.close if client
69
+ end
70
+ end # process! with no processors
71
+
61
72
  describe "for process!" do
62
73
  before do
63
74
  $foo = []
@@ -107,6 +118,54 @@ describe Beaneater::Jobs do
107
118
  end
108
119
  end # for_process!
109
120
 
121
+ describe "for process! when it deletes or releases a job" do
122
+ before do
123
+ $ran = []
124
+ cleanup_tubes!(['tube_done', 'tube_retry'])
125
+ @sent = []
126
+ sent = @sent
127
+ @beanstalk.connection.define_singleton_method(:transmit) do |command, **options|
128
+ sent << command.to_s
129
+ super(command, **options)
130
+ end
131
+ @jobs.register('tube_retry', :retry_on => [Timeout::Error], :max_retries => 1) do |job|
132
+ $ran << job.id
133
+ raise Timeout::Error
134
+ end
135
+ @jobs.register('tube_done') { |job| $ran << job.id; @jobs.stop! if $ran.size == 4 }
136
+ @retry_id = @beanstalk.tubes.find('tube_retry').put("retry", :pri => 1)[:id]
137
+ @done_ids = 2.times.map { |i| @beanstalk.tubes.find('tube_done').put("done #{i}", :pri => 2)[:id] }
138
+ Timeout.timeout(10) { @jobs.process!(:release_delay => 0, :reserve_timeout => 1) }
139
+ end
140
+
141
+ after do
142
+ connection = @beanstalk.connection
143
+ connection.singleton_class.send(:remove_method, :transmit) if connection.singleton_methods(false).include?(:transmit)
144
+ end
145
+
146
+ # The commands naming job id after the given command, up to the next reserve
147
+ def sent_about(id, command)
148
+ start = @sent.index(command)
149
+ refute_nil start, "#{command.inspect} was not sent: #{@sent.inspect}"
150
+ @sent.drop(start + 1).take_while { |c| !c.start_with?('reserve') }.select { |c| c.split(' ')[1] == id.to_s }
151
+ end
152
+
153
+ it "sends nothing more about a job it deleted" do
154
+ @done_ids.each do |id|
155
+ assert_empty sent_about(id, "delete #{id}"), "sent after deleting job #{id}: #{@sent.inspect}"
156
+ end
157
+ stats = @beanstalk.tubes.find('tube_done').stats
158
+ assert_equal [0, 0, 0], [stats.current_jobs_ready, stats.current_jobs_reserved, stats.current_jobs_buried]
159
+ end
160
+
161
+ it "sends nothing more about a job it released, and buries it when it runs out of retries" do
162
+ assert_empty sent_about(@retry_id, "release #{@retry_id} 1 0"), "sent after releasing job #{@retry_id}: #{@sent.inspect}"
163
+ assert_equal [@retry_id, @retry_id], $ran.first(2)
164
+ job = @beanstalk.jobs.find(@retry_id)
165
+ assert_equal ['buried', 1], [job.stats.state, job.stats.releases]
166
+ end
167
+ end # process! when it deletes or releases a job
168
+
110
169
  describe "for process! with a dashed tube name" do
111
170
  before do
112
171
  $ran = []
@@ -34,6 +34,19 @@ describe Beaneater::StatStruct do
34
34
  assert_equal 'demo', @struct['under-score']
35
35
  assert_equal 'demo', @struct[:"under-score"]
36
36
  end
37
+
38
+ it "should read a stat whose name is also a method name" do
39
+ struct = Beaneater::StatStruct.from_hash('hash' => 'h', 'class' => 'c')
40
+ assert_equal 'h', struct['hash']
41
+ assert_equal 'c', struct[:class]
42
+ end
43
+
44
+ it "should return nil for a key that is not a stat" do
45
+ [:object_id, 'send', 'freeze', 'foo=', 'no such key'].each do |key|
46
+ assert_nil @struct[key], "Expected nil for #{key.inspect}"
47
+ end
48
+ refute @struct.frozen?
49
+ end
37
50
  end # []
38
51
 
39
52
  describe "for #keys" do
@@ -46,6 +59,18 @@ describe Beaneater::StatStruct do
46
59
  end
47
60
  end # keys
48
61
 
62
+ describe "for #respond_to?" do
63
+ it "should respond to a key before it is first read" do
64
+ struct = Beaneater::StatStruct.from_hash('rusage-utime' => 0.5)
65
+ assert struct.respond_to?(:rusage_utime), "Expected struct to respond to rusage_utime"
66
+ assert_equal 0.5, struct.method(:rusage_utime).call
67
+ end
68
+
69
+ it "should not respond to a name that is not a key" do
70
+ refute @struct.respond_to?(:no_such_key)
71
+ end
72
+ end # respond_to?
73
+
49
74
  describe "for #to_h" do
50
75
  it "should return 4 keys / values" do
51
76
  assert_equal 4, @struct.to_h.size
data/test/stats_test.rb CHANGED
@@ -42,4 +42,20 @@ describe Beaneater::Stats do
42
42
  assert_raises(NoMethodError) { @stats.cmd }
43
43
  end
44
44
  end # method_missing
45
+
46
+ describe 'for #respond_to?' do
47
+ before do
48
+ connection = stub(:transmit => { :body => { 'max-job-size' => 65535 }, :status => "OK" })
49
+ @stats = Beaneater::Stats.new(stub(:connection => connection))
50
+ end
51
+
52
+ it "should respond to a stats key before it is first read" do
53
+ assert @stats.respond_to?(:max_job_size), "Expected stats to respond to max_job_size"
54
+ assert_equal 65535, @stats.method(:max_job_size).call
55
+ end
56
+
57
+ it "should not respond to a name that is not a stats key" do
58
+ refute @stats.respond_to?(:no_such_stat)
59
+ end
60
+ end # respond_to?
45
61
  end # Beaneater::Stats
data/test/tubes_test.rb CHANGED
@@ -46,6 +46,13 @@ describe Beaneater::Tubes do
46
46
  it 'should raise invalid name for bad tube' do
47
47
  assert_raises(Beaneater::InvalidTubeName) { @beanstalk.tubes.watch('; ') }
48
48
  end
49
+
50
+ it 'should remember each watched tube once, by name, for a reconnect to restore' do
51
+ @beanstalk.tubes.watch('a')
52
+ @beanstalk.tubes.watch('a')
53
+ @beanstalk.tubes.watch(:a)
54
+ assert_equal ['default', 'a'], @beanstalk.connection.tubes_watched
55
+ end
49
56
  end # watch! & watched
50
57
 
51
58
  describe "for #all" do
@@ -123,6 +130,13 @@ describe Beaneater::Tubes do
123
130
  @beanstalk.tubes.ignore('foo')
124
131
  assert_equal ['default', 'bar'].sort, @beanstalk.tubes.watched.map(&:name).sort
125
132
  end
133
+
134
+ it 'should forget an ignored tube however its name is given' do
135
+ @beanstalk.tubes.watch('foo')
136
+ @beanstalk.tubes.watch('bar')
137
+ @beanstalk.tubes.ignore(:foo)
138
+ assert_equal ['default', 'bar'], @beanstalk.connection.tubes_watched
139
+ end
126
140
  end # ignore
127
141
 
128
142
  describe "for #reserve" do
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: beaneater
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.0
4
+ version: 1.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nico Taing
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-31 00:00:00.000000000 Z
11
+ date: 2026-11-05 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: minitest
@@ -89,7 +89,6 @@ extra_rdoc_files: []
89
89
  files:
90
90
  - ".github/workflows/ruby.yml"
91
91
  - ".gitignore"
92
- - ".travis.yml"
93
92
  - ".yardopts"
94
93
  - CHANGELOG.md
95
94
  - Gemfile
@@ -100,6 +99,7 @@ files:
100
99
  - beaneater.gemspec
101
100
  - examples/demo.rb
102
101
  - lib/beaneater.rb
102
+ - lib/beaneater/arguments.rb
103
103
  - lib/beaneater/configuration.rb
104
104
  - lib/beaneater/connection.rb
105
105
  - lib/beaneater/errors.rb
@@ -113,6 +113,7 @@ files:
113
113
  - lib/beaneater/tube/collection.rb
114
114
  - lib/beaneater/tube/record.rb
115
115
  - lib/beaneater/version.rb
116
+ - test/arguments_test.rb
116
117
  - test/beaneater_test.rb
117
118
  - test/connection_test.rb
118
119
  - test/errors_test.rb
@@ -124,10 +125,14 @@ files:
124
125
  - test/test_helper.rb
125
126
  - test/tube_test.rb
126
127
  - test/tubes_test.rb
127
- homepage: ''
128
+ homepage: https://github.com/beanstalkd/beaneater
128
129
  licenses:
129
130
  - MIT
130
- metadata: {}
131
+ metadata:
132
+ changelog_uri: https://github.com/beanstalkd/beaneater/blob/master/CHANGELOG.md
133
+ source_code_uri: https://github.com/beanstalkd/beaneater
134
+ bug_tracker_uri: https://github.com/beanstalkd/beaneater/issues
135
+ rubygems_mfa_required: 'true'
131
136
  post_install_message:
132
137
  rdoc_options: []
133
138
  require_paths:
@@ -148,6 +153,7 @@ signing_key:
148
153
  specification_version: 4
149
154
  summary: Simple beanstalkd client for ruby.
150
155
  test_files:
156
+ - test/arguments_test.rb
151
157
  - test/beaneater_test.rb
152
158
  - test/connection_test.rb
153
159
  - test/errors_test.rb
data/.travis.yml DELETED
@@ -1,15 +0,0 @@
1
- language: ruby
2
- rvm:
3
- - 2.5
4
- - 2.6
5
- - 2.7
6
- - 3.0
7
- before_install:
8
- - curl -L https://github.com/kr/beanstalkd/archive/v1.9.tar.gz | tar xz -C /tmp
9
- - cd /tmp/beanstalkd-1.9/
10
- - make
11
- - ./beanstalkd &
12
- - cd $TRAVIS_BUILD_DIR
13
- script:
14
- - bundle install
15
- - bundle exec rake test:full