nogara-resque-lonely_job 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in resque-lonelyjob.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Jonathan R. Wallace
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,120 @@
1
+ # Resque::LonelyJob
2
+
3
+ A [Resque](https://github.com/defunkt/resque) plugin. Requires Resque >= 1.20.0.
4
+
5
+ Ensures that for a given queue, only one worker is working on a job at any given
6
+ time.
7
+
8
+ This differs from [resque-lock](from https://github.com/defunkt/resque-lock) and
9
+ [resque-loner](http://github.com/jayniz/resque-loner) in that the same job may
10
+ be queued multiple times but you're guaranteed that first job queued will run to
11
+ completion before subsequent jobs are run.
12
+
13
+ However, it is possible that subsequent jobs are re-ordered depending upon
14
+ worker behavior. Therefore it is recommended that the payload for jobs be
15
+ stored in a separate redis list distinct from the Resque queue (see Example #3).
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ gem 'resque-lonely_job'
22
+
23
+ And then execute:
24
+
25
+ $ bundle
26
+
27
+ Or install it yourself as:
28
+
29
+ $ gem install resque-lonely_job
30
+
31
+ ## Usage
32
+
33
+ #### Example #1 -- One job running per queue
34
+
35
+ require 'resque/plugins/lonely_job'
36
+
37
+ class StrictlySerialJob
38
+ extend Resque::Plugins::LonelyJob
39
+
40
+ @queue = :serial_work
41
+
42
+ def self.perform
43
+ # only one at a time in this block, no parallelism allowed for this
44
+ # particular queue
45
+ end
46
+ end
47
+
48
+ #### Example #2 -- One job running per user-defined attribute
49
+
50
+ Let's say you want the serial constraint to apply at a more granular
51
+ level. Instead of applying at the queue level, you can overwrite the .redis\_key
52
+ method.
53
+
54
+ require 'resque/plugins/lonely_job'
55
+
56
+ class StrictlySerialJob
57
+ extend Resque::Plugins::LonelyJob
58
+
59
+ @queue = :serial_work
60
+
61
+ # Returns a string that will be used as the redis key
62
+ # NOTE: it is recommended to prefix your string with the 'lonely_job:' to
63
+ # namespace your key!
64
+ def self.redis_key(account_id, *args)
65
+ "lonely_job:strictly_serial_job:#{account_id}"
66
+ end
67
+
68
+ # Overwrite reenqueue to lpush instead of default rpush. This attempts to
69
+ # preserve job ordering but job order is *NOT* guaranteed.
70
+ def self.reenqueue(*args)
71
+ Resque.redis.lpush("queue:#{Resque.queue_from_class(self)}", Resque.encode(class: self, args: args))
72
+ end
73
+
74
+ def self.perform(account_id, *args)
75
+ # only one at a time in this block, no parallelism allowed for this
76
+ # particular redis_key
77
+ end
78
+ end
79
+
80
+ *NOTE*: Without careful consideration of your problem domain, worker starvation
81
+ and/or unfairness is possible for jobs in this example. Imagine a scenario
82
+ where you have three jobs in the queue with two resque workers:
83
+
84
+ +---------------------------------------------------+
85
+ | :serial_work |
86
+ |---------------------------------------------------|
87
+ | | | | |
88
+ | redis_key: | redis_key: | redis_key: | ... |
89
+ | A | A | B | |
90
+ | | | | |
91
+ | job 1 | job 2 | job 3 | |
92
+ +---------------------------------------------------+
93
+ ^
94
+ |
95
+ Possible starvation +-----------+
96
+ for this job and
97
+ subsequent ones
98
+
99
+
100
+ When the first worker grabs job 1, it'll acquire the mutex for processing
101
+ redis\_key A. The second worker tries to grab the next job off the queue but
102
+ is unable to acquire the mutex for redis\_key A so it places job 2 back at the
103
+ head of the :serial\_work queue. Until worker 1 completes job 1 and releases
104
+ the mutex for redis\_key A, no work will be done in this queue.
105
+
106
+ This issue may be avoided by employing dynamic queues,
107
+ http://blog.kabisa.nl/2010/03/16/dynamic-queue-assignment-for-resque-jobs/,
108
+ where the queue is a one to one mapping to the redis\_key.
109
+
110
+ #### Example #3 -- One job running per user-defined attribute with job ordering preserved
111
+
112
+ TODO
113
+
114
+ ## Contributing
115
+
116
+ 1. Fork it
117
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
118
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
119
+ 4. Push to the branch (`git push origin my-new-feature`)
120
+ 5. Create new Pull Request
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require "rspec/core/rake_task"
4
+
5
+ RSpec::Core::RakeTask.new
6
+
7
+ task :default => :spec
8
+ task :test => :spec
@@ -0,0 +1,53 @@
1
+ require 'resque-lonely_job/version'
2
+
3
+ module Resque
4
+ module Plugins
5
+ module LonelyJob
6
+ LOCK_TIMEOUT = 60 * 60 * 24 * 5 # 5 days
7
+
8
+ def lock_timeout
9
+ Time.now.utc + LOCK_TIMEOUT + 1
10
+ end
11
+
12
+ # Overwrite this method to uniquely identify which mutex should be used
13
+ # for a resque worker.
14
+ def redis_key(*args)
15
+ "lonely_job:#{@queue}"
16
+ end
17
+
18
+ def can_lock_queue?(*args)
19
+ Resque.redis.setnx(redis_key(*args), lock_timeout)
20
+ end
21
+
22
+ def unlock_queue(*args)
23
+ Resque.redis.del(redis_key(*args))
24
+ end
25
+
26
+ # Unfortunately, there's not a Resque interface for lpush so we have to
27
+ # role our own. This is based on Resque.push but we don't need to
28
+ # call Resque.watch_queue as the queue should already exist if we're
29
+ # unable to get the lock.
30
+ def reenqueue(*args)
31
+ Resque.enqueue(self, *args)
32
+ end
33
+
34
+ def before_perform(*args)
35
+ unless can_lock_queue?(*args)
36
+ # can't get the lock, so re-enqueue the task
37
+ reenqueue(*args)
38
+
39
+ # and don't perform
40
+ raise Resque::Job::DontPerform
41
+ end
42
+ end
43
+
44
+ def around_perform(*args)
45
+ begin
46
+ yield
47
+ ensure
48
+ unlock_queue(*args)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,7 @@
1
+ module Resque
2
+ module Plugins
3
+ module LonelyJob
4
+ VERSION = "0.0.3"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,41 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path('../lib/resque-lonely_job/version', __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Jonathan R. Wallace"]
6
+ gem.email = ["jonathan.wallace@gmail.com"]
7
+ gem.summary = %q{A resque plugin that ensures that only one job for a given queue will be running on any worker at a given time.}
8
+ gem.homepage = "http://github.com/wallace/resque-lonely_job"
9
+
10
+ gem.files = `git ls-files`.split($\)
11
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
12
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
13
+ gem.name = "nogara-resque-lonely_job"
14
+ gem.require_paths = ["lib"]
15
+ gem.version = Resque::Plugins::LonelyJob::VERSION
16
+
17
+ gem.add_dependency 'resque', '~> 1.21.0'
18
+ gem.add_development_dependency 'mock_redis', '~> 0.4.1'
19
+ gem.add_development_dependency 'rake'
20
+ gem.add_development_dependency 'rspec'
21
+ gem.add_development_dependency 'debugger'
22
+
23
+ gem.description = <<desc
24
+ Ensures that for a given queue, only one worker is working on a job at any given time.
25
+
26
+ Example:
27
+
28
+ require 'resque/plugins/lonely_job'
29
+
30
+ class StrictlySerialJob
31
+ extend Resque::Plugins::LonelyJob
32
+
33
+ @queue = :serial_work
34
+
35
+ def self.perform
36
+ # only one at a time in this block, no parallelism allowed for this
37
+ # particular queue
38
+ end
39
+ end
40
+ desc
41
+ end
@@ -0,0 +1,134 @@
1
+ require 'spec_helper'
2
+
3
+ class SerialJob
4
+ extend Resque::Plugins::LonelyJob
5
+ @queue = :serial_work
6
+
7
+ def self.perform(*args); end
8
+ end
9
+
10
+ class SerialJobWithCustomRedisKey
11
+ extend Resque::Plugins::LonelyJob
12
+ @queue = :serial_work
13
+
14
+ def redis_key(account_id, *args)
15
+ "lonely_job:#{@queue}:#{account_id}"
16
+ end
17
+
18
+ def self.perform(account_id, *args); end
19
+ end
20
+
21
+ describe Resque::Plugins::LonelyJob do
22
+ before do
23
+ Resque.redis.flushall
24
+ end
25
+
26
+ describe ".can_lock_queue?" do
27
+ it 'can lock a queue' do
28
+ SerialJob.can_lock_queue?(:serial_work).should be_true
29
+ end
30
+
31
+ it 'cannot lock an already locked queue' do
32
+ SerialJob.can_lock_queue?(:serial_work).should be_true
33
+ SerialJob.can_lock_queue?(:serial_work).should be_false
34
+ end
35
+ end
36
+
37
+ describe ".perform" do
38
+ describe "using the default redis key" do
39
+ it 'should lock and unlock the queue' do
40
+ job = Resque::Job.new(:serial_work, { 'class' => 'SerialJob', 'args' => %w[account_one job_one] })
41
+
42
+ # job is the first SerialJob to run so it can lock the queue and perform
43
+ SerialJob.should_receive(:can_lock_queue?).and_return(true)
44
+
45
+ # but it should also clean up after itself
46
+ SerialJob.should_receive(:unlock_queue)
47
+
48
+ job.perform
49
+ end
50
+
51
+ it 'should clean up lock even with catastrophic job failure' do
52
+ job = Resque::Job.new(:serial_work, { 'class' => 'SerialJob', 'args' => %w[account_one job_one] })
53
+
54
+ # job is the first SerialJob to run so it can lock the queue and perform
55
+ SerialJob.should_receive(:can_lock_queue?).and_return(true)
56
+
57
+ # but we have a catastrophic job failure
58
+ SerialJob.should_receive(:perform).and_raise(Exception)
59
+
60
+ # and still it should clean up after itself
61
+ SerialJob.should_receive(:unlock_queue)
62
+
63
+ # unfortunately, the job will be lost but resque doesn't guarantee jobs
64
+ # aren't lost
65
+ -> { job.perform }.should raise_error(Exception)
66
+ end
67
+
68
+ it 'should place self at the end of the queue if unable to acquire the lock' do
69
+ job1_payload = %w[account_one job_one]
70
+ job2_payload = %w[account_one job_two]
71
+ Resque::Job.create(:serial_work, 'SerialJob', job1_payload)
72
+ Resque::Job.create(:serial_work, 'SerialJob', job2_payload)
73
+
74
+ SerialJob.should_receive(:can_lock_queue?).and_return(false)
75
+
76
+ # perform returns false when DontPerform exception is raised in
77
+ # before_perform callback
78
+ job1 = Resque.reserve(:serial_work)
79
+ job1.perform.should be_false
80
+
81
+ first_queue_element = Resque.reserve(:serial_work)
82
+ first_queue_element.payload["args"].should == [job2_payload]
83
+ end
84
+ end
85
+
86
+ describe "with a custom redis_key" do
87
+ it 'should lock and unlock the queue' do
88
+ job = Resque::Job.new(:serial_work, { 'class' => 'SerialJobWithCustomRedisKey', 'args' => %w[account_one job_one] })
89
+
90
+ # job is the first SerialJobWithCustomRedisKey to run so it can lock the queue and perform
91
+ SerialJobWithCustomRedisKey.should_receive(:can_lock_queue?).and_return(true)
92
+
93
+ # but it should also clean up after itself
94
+ SerialJobWithCustomRedisKey.should_receive(:unlock_queue)
95
+
96
+ job.perform
97
+ end
98
+
99
+ it 'should clean up lock even with catastrophic job failure' do
100
+ job = Resque::Job.new(:serial_work, { 'class' => 'SerialJobWithCustomRedisKey', 'args' => %w[account_one job_one] })
101
+
102
+ # job is the first SerialJobWithCustomRedisKey to run so it can lock the queue and perform
103
+ SerialJobWithCustomRedisKey.should_receive(:can_lock_queue?).and_return(true)
104
+
105
+ # but we have a catastrophic job failure
106
+ SerialJobWithCustomRedisKey.should_receive(:perform).and_raise(Exception)
107
+
108
+ # and still it should clean up after itself
109
+ SerialJobWithCustomRedisKey.should_receive(:unlock_queue)
110
+
111
+ # unfortunately, the job will be lost but resque doesn't guarantee jobs
112
+ # aren't lost
113
+ -> { job.perform }.should raise_error(Exception)
114
+ end
115
+
116
+ it 'should place self at the end of the queue if unable to acquire the lock' do
117
+ job1_payload = %w[account_one job_one]
118
+ job2_payload = %w[account_one job_two]
119
+ Resque::Job.create(:serial_work, 'SerialJobWithCustomRedisKey', job1_payload)
120
+ Resque::Job.create(:serial_work, 'SerialJobWithCustomRedisKey', job2_payload)
121
+
122
+ SerialJobWithCustomRedisKey.should_receive(:can_lock_queue?).and_return(false)
123
+
124
+ # perform returns false when DontPerform exception is raised in
125
+ # before_perform callback
126
+ job1 = Resque.reserve(:serial_work)
127
+ job1.perform.should be_false
128
+
129
+ first_queue_element = Resque.reserve(:serial_work)
130
+ first_queue_element.payload["args"].should == [job2_payload]
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,13 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+ require 'rspec'
4
+
5
+ require 'mock_redis'
6
+ require 'resque'
7
+ require 'resque-lonely_job'
8
+
9
+ RSpec.configure do |config|
10
+ config.before(:suite) do
11
+ Resque.redis = MockRedis.new
12
+ end
13
+ end
metadata ADDED
@@ -0,0 +1,142 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nogara-resque-lonely_job
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.3
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Jonathan R. Wallace
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-08-07 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: resque
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 1.21.0
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: 1.21.0
30
+ - !ruby/object:Gem::Dependency
31
+ name: mock_redis
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ~>
36
+ - !ruby/object:Gem::Version
37
+ version: 0.4.1
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ~>
44
+ - !ruby/object:Gem::Version
45
+ version: 0.4.1
46
+ - !ruby/object:Gem::Dependency
47
+ name: rake
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ - !ruby/object:Gem::Dependency
63
+ name: rspec
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ - !ruby/object:Gem::Dependency
79
+ name: debugger
80
+ requirement: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ type: :development
87
+ prerelease: false
88
+ version_requirements: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ! '>='
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ description: ! "Ensures that for a given queue, only one worker is working on a job
95
+ at any given time.\n\nExample:\n\n require 'resque/plugins/lonely_job'\n\n class
96
+ StrictlySerialJob\n extend Resque::Plugins::LonelyJob\n\n @queue = :serial_work\n\n
97
+ \ def self.perform\n # only one at a time in this block, no parallelism allowed
98
+ for this\n # particular queue\n end\n end\n"
99
+ email:
100
+ - jonathan.wallace@gmail.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - .gitignore
106
+ - Gemfile
107
+ - LICENSE
108
+ - README.md
109
+ - Rakefile
110
+ - lib/resque-lonely_job.rb
111
+ - lib/resque-lonely_job/version.rb
112
+ - resque-lonely_job.gemspec
113
+ - spec/lib/lonely_job_spec.rb
114
+ - spec/spec_helper.rb
115
+ homepage: http://github.com/wallace/resque-lonely_job
116
+ licenses: []
117
+ post_install_message:
118
+ rdoc_options: []
119
+ require_paths:
120
+ - lib
121
+ required_ruby_version: !ruby/object:Gem::Requirement
122
+ none: false
123
+ requirements:
124
+ - - ! '>='
125
+ - !ruby/object:Gem::Version
126
+ version: '0'
127
+ required_rubygems_version: !ruby/object:Gem::Requirement
128
+ none: false
129
+ requirements:
130
+ - - ! '>='
131
+ - !ruby/object:Gem::Version
132
+ version: '0'
133
+ requirements: []
134
+ rubyforge_project:
135
+ rubygems_version: 1.8.24
136
+ signing_key:
137
+ specification_version: 3
138
+ summary: A resque plugin that ensures that only one job for a given queue will be
139
+ running on any worker at a given time.
140
+ test_files:
141
+ - spec/lib/lonely_job_spec.rb
142
+ - spec/spec_helper.rb