delayed_job 1.8.5 → 2.0.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.
@@ -0,0 +1,246 @@
1
+ shared_examples_for 'a backend' do
2
+ def create_job(opts = {})
3
+ @backend.create(opts.merge(:payload_object => SimpleJob.new))
4
+ end
5
+
6
+ before do
7
+ Delayed::Worker.max_priority = nil
8
+ Delayed::Worker.min_priority = nil
9
+ SimpleJob.runs = 0
10
+ end
11
+
12
+ it "should set run_at automatically if not set" do
13
+ @backend.create(:payload_object => ErrorJob.new ).run_at.should_not be_nil
14
+ end
15
+
16
+ it "should not set run_at automatically if already set" do
17
+ later = @backend.db_time_now + 5.minutes
18
+ @backend.create(:payload_object => ErrorJob.new, :run_at => later).run_at.should be_close(later, 1)
19
+ end
20
+
21
+ it "should raise ArgumentError when handler doesn't respond_to :perform" do
22
+ lambda { @backend.enqueue(Object.new) }.should raise_error(ArgumentError)
23
+ end
24
+
25
+ it "should increase count after enqueuing items" do
26
+ @backend.enqueue SimpleJob.new
27
+ @backend.count.should == 1
28
+ end
29
+
30
+ it "should be able to set priority when enqueuing items" do
31
+ @job = @backend.enqueue SimpleJob.new, 5
32
+ @job.priority.should == 5
33
+ end
34
+
35
+ it "should be able to set run_at when enqueuing items" do
36
+ later = @backend.db_time_now + 5.minutes
37
+ @job = @backend.enqueue SimpleJob.new, 5, later
38
+ @job.run_at.should be_close(later, 1)
39
+ end
40
+
41
+ it "should work with jobs in modules" do
42
+ M::ModuleJob.runs = 0
43
+ job = @backend.enqueue M::ModuleJob.new
44
+ lambda { job.invoke_job }.should change { M::ModuleJob.runs }.from(0).to(1)
45
+ end
46
+
47
+ it "should raise an DeserializationError when the job class is totally unknown" do
48
+ job = @backend.new :handler => "--- !ruby/object:JobThatDoesNotExist {}"
49
+ lambda { job.payload_object.perform }.should raise_error(Delayed::Backend::DeserializationError)
50
+ end
51
+
52
+ it "should try to load the class when it is unknown at the time of the deserialization" do
53
+ job = @backend.new :handler => "--- !ruby/object:JobThatDoesNotExist {}"
54
+ job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true)
55
+ lambda { job.payload_object.perform }.should raise_error(Delayed::Backend::DeserializationError)
56
+ end
57
+
58
+ it "should try include the namespace when loading unknown objects" do
59
+ job = @backend.new :handler => "--- !ruby/object:Delayed::JobThatDoesNotExist {}"
60
+ job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true)
61
+ lambda { job.payload_object.perform }.should raise_error(Delayed::Backend::DeserializationError)
62
+ end
63
+
64
+ it "should also try to load structs when they are unknown (raises TypeError)" do
65
+ job = @backend.new :handler => "--- !ruby/struct:JobThatDoesNotExist {}"
66
+ job.should_receive(:attempt_to_load).with('JobThatDoesNotExist').and_return(true)
67
+ lambda { job.payload_object.perform }.should raise_error(Delayed::Backend::DeserializationError)
68
+ end
69
+
70
+ it "should try include the namespace when loading unknown structs" do
71
+ job = @backend.new :handler => "--- !ruby/struct:Delayed::JobThatDoesNotExist {}"
72
+ job.should_receive(:attempt_to_load).with('Delayed::JobThatDoesNotExist').and_return(true)
73
+ lambda { job.payload_object.perform }.should raise_error(Delayed::Backend::DeserializationError)
74
+ end
75
+
76
+ describe "find_available" do
77
+ it "should not find failed jobs" do
78
+ @job = create_job :attempts => 50, :failed_at => @backend.db_time_now
79
+ @backend.find_available('worker', 5, 1.second).should_not include(@job)
80
+ end
81
+
82
+ it "should not find jobs scheduled for the future" do
83
+ @job = create_job :run_at => (@backend.db_time_now + 1.minute)
84
+ @backend.find_available('worker', 5, 4.hours).should_not include(@job)
85
+ end
86
+
87
+ it "should not find jobs locked by another worker" do
88
+ @job = create_job(:locked_by => 'other_worker', :locked_at => @backend.db_time_now - 1.minute)
89
+ @backend.find_available('worker', 5, 4.hours).should_not include(@job)
90
+ end
91
+
92
+ it "should find open jobs" do
93
+ @job = create_job
94
+ @backend.find_available('worker', 5, 4.hours).should include(@job)
95
+ end
96
+
97
+ it "should find expired jobs" do
98
+ @job = create_job(:locked_by => 'worker', :locked_at => @backend.db_time_now - 2.minutes)
99
+ @backend.find_available('worker', 5, 1.minute).should include(@job)
100
+ end
101
+
102
+ it "should find own jobs" do
103
+ @job = create_job(:locked_by => 'worker', :locked_at => (@backend.db_time_now - 1.minutes))
104
+ @backend.find_available('worker', 5, 4.hours).should include(@job)
105
+ end
106
+
107
+ it "should find only the right amount of jobs" do
108
+ 10.times { create_job }
109
+ @backend.find_available('worker', 7, 4.hours).should have(7).jobs
110
+ end
111
+ end
112
+
113
+ context "when another worker is already performing an task, it" do
114
+
115
+ before :each do
116
+ @job = @backend.create :payload_object => SimpleJob.new, :locked_by => 'worker1', :locked_at => @backend.db_time_now - 5.minutes
117
+ end
118
+
119
+ it "should not allow a second worker to get exclusive access" do
120
+ @job.lock_exclusively!(4.hours, 'worker2').should == false
121
+ end
122
+
123
+ it "should allow a second worker to get exclusive access if the timeout has passed" do
124
+ @job.lock_exclusively!(1.minute, 'worker2').should == true
125
+ end
126
+
127
+ it "should be able to get access to the task if it was started more then max_age ago" do
128
+ @job.locked_at = 5.hours.ago
129
+ @job.save
130
+
131
+ @job.lock_exclusively! 4.hours, 'worker2'
132
+ @job.reload
133
+ @job.locked_by.should == 'worker2'
134
+ @job.locked_at.should > 1.minute.ago
135
+ end
136
+
137
+ it "should not be found by another worker" do
138
+ @backend.find_available('worker2', 1, 6.minutes).length.should == 0
139
+ end
140
+
141
+ it "should be found by another worker if the time has expired" do
142
+ @backend.find_available('worker2', 1, 4.minutes).length.should == 1
143
+ end
144
+
145
+ it "should be able to get exclusive access again when the worker name is the same" do
146
+ @job.lock_exclusively!(5.minutes, 'worker1').should be_true
147
+ @job.lock_exclusively!(5.minutes, 'worker1').should be_true
148
+ @job.lock_exclusively!(5.minutes, 'worker1').should be_true
149
+ end
150
+ end
151
+
152
+ context "when another worker has worked on a task since the job was found to be available, it" do
153
+
154
+ before :each do
155
+ @job = @backend.create :payload_object => SimpleJob.new
156
+ @job_copy_for_worker_2 = @backend.find(@job.id)
157
+ end
158
+
159
+ it "should not allow a second worker to get exclusive access if already successfully processed by worker1" do
160
+ @job.destroy
161
+ @job_copy_for_worker_2.lock_exclusively!(4.hours, 'worker2').should == false
162
+ end
163
+
164
+ it "should not allow a second worker to get exclusive access if failed to be processed by worker1 and run_at time is now in future (due to backing off behaviour)" do
165
+ @job.update_attributes(:attempts => 1, :run_at => 1.day.from_now)
166
+ @job_copy_for_worker_2.lock_exclusively!(4.hours, 'worker2').should == false
167
+ end
168
+ end
169
+
170
+ context "#name" do
171
+ it "should be the class name of the job that was enqueued" do
172
+ @backend.create(:payload_object => ErrorJob.new ).name.should == 'ErrorJob'
173
+ end
174
+
175
+ it "should be the method that will be called if its a performable method object" do
176
+ @job = Story.send_later(:create)
177
+ @job.name.should == "Story.create"
178
+ end
179
+
180
+ it "should be the instance method that will be called if its a performable method object" do
181
+ @job = Story.create(:text => "...").send_later(:save)
182
+ @job.name.should == 'Story#save'
183
+ end
184
+ end
185
+
186
+ context "worker prioritization" do
187
+ before(:each) do
188
+ Delayed::Worker.max_priority = nil
189
+ Delayed::Worker.min_priority = nil
190
+ end
191
+
192
+ it "should fetch jobs ordered by priority" do
193
+ 10.times { @backend.enqueue SimpleJob.new, rand(10) }
194
+ jobs = @backend.find_available('worker', 10)
195
+ jobs.size.should == 10
196
+ jobs.each_cons(2) do |a, b|
197
+ a.priority.should <= b.priority
198
+ end
199
+ end
200
+
201
+ it "should only find jobs greater than or equal to min priority" do
202
+ min = 5
203
+ Delayed::Worker.min_priority = min
204
+ 10.times {|i| @backend.enqueue SimpleJob.new, i }
205
+ jobs = @backend.find_available('worker', 10)
206
+ jobs.each {|job| job.priority.should >= min}
207
+ end
208
+
209
+ it "should only find jobs less than or equal to max priority" do
210
+ max = 5
211
+ Delayed::Worker.max_priority = max
212
+ 10.times {|i| @backend.enqueue SimpleJob.new, i }
213
+ jobs = @backend.find_available('worker', 10)
214
+ jobs.each {|job| job.priority.should <= max}
215
+ end
216
+ end
217
+
218
+ context "clear_locks!" do
219
+ before do
220
+ @job = create_job(:locked_by => 'worker', :locked_at => @backend.db_time_now)
221
+ end
222
+
223
+ it "should clear locks for the given worker" do
224
+ @backend.clear_locks!('worker')
225
+ @backend.find_available('worker2', 5, 1.minute).should include(@job)
226
+ end
227
+
228
+ it "should not clear locks for other workers" do
229
+ @backend.clear_locks!('worker1')
230
+ @backend.find_available('worker1', 5, 1.minute).should_not include(@job)
231
+ end
232
+ end
233
+
234
+ context "unlock" do
235
+ before do
236
+ @job = create_job(:locked_by => 'worker', :locked_at => @backend.db_time_now)
237
+ end
238
+
239
+ it "should clear locks" do
240
+ @job.unlock
241
+ @job.locked_by.should be_nil
242
+ @job.locked_at.should be_nil
243
+ end
244
+ end
245
+
246
+ end
@@ -1,115 +1,24 @@
1
- require File.dirname(__FILE__) + '/database'
2
-
3
- class SimpleJob
4
- cattr_accessor :runs; self.runs = 0
5
- def perform; @@runs += 1; end
6
- end
7
-
8
- class RandomRubyObject
9
- def say_hello
10
- 'hello'
11
- end
12
- end
13
-
14
- class ErrorObject
15
-
16
- def throw
17
- raise ActiveRecord::RecordNotFound, '...'
18
- false
19
- end
20
-
21
- end
22
-
23
- class StoryReader
24
-
25
- def read(story)
26
- "Epilog: #{story.tell}"
27
- end
28
-
29
- end
30
-
31
- class StoryReader
32
-
33
- def read(story)
34
- "Epilog: #{story.tell}"
35
- end
36
-
37
- end
1
+ require 'spec_helper'
38
2
 
39
3
  describe 'random ruby objects' do
40
4
  before { Delayed::Job.delete_all }
41
5
 
42
6
  it "should respond_to :send_later method" do
43
-
44
- RandomRubyObject.new.respond_to?(:send_later)
45
-
7
+ Object.new.respond_to?(:send_later)
46
8
  end
47
9
 
48
10
  it "should raise a ArgumentError if send_later is called but the target method doesn't exist" do
49
- lambda { RandomRubyObject.new.send_later(:method_that_deos_not_exist) }.should raise_error(NoMethodError)
11
+ lambda { Object.new.send_later(:method_that_deos_not_exist) }.should raise_error(NoMethodError)
50
12
  end
51
13
 
52
14
  it "should add a new entry to the job table when send_later is called on it" do
53
- Delayed::Job.count.should == 0
54
-
55
- RandomRubyObject.new.send_later(:to_s)
56
-
57
- Delayed::Job.count.should == 1
15
+ lambda { Object.new.send_later(:to_s) }.should change { Delayed::Job.count }.by(1)
58
16
  end
59
17
 
60
18
  it "should add a new entry to the job table when send_later is called on the class" do
61
- Delayed::Job.count.should == 0
62
-
63
- RandomRubyObject.send_later(:to_s)
64
-
65
- Delayed::Job.count.should == 1
66
- end
67
-
68
- it "should run get the original method executed when the job is performed" do
69
-
70
- RandomRubyObject.new.send_later(:say_hello)
71
-
72
- Delayed::Job.count.should == 1
73
- end
74
-
75
- it "should ignore ActiveRecord::RecordNotFound errors because they are permanent" do
76
-
77
- ErrorObject.new.send_later(:throw)
78
-
79
- Delayed::Job.count.should == 1
80
-
81
- Delayed::Job.reserve_and_run_one_job
82
-
83
- Delayed::Job.count.should == 0
84
-
85
- end
86
-
87
- it "should store the object as string if its an active record" do
88
- story = Story.create :text => 'Once upon...'
89
- story.send_later(:tell)
90
-
91
- job = Delayed::Job.find(:first)
92
- job.payload_object.class.should == Delayed::PerformableMethod
93
- job.payload_object.object.should == "AR:Story:#{story.id}"
94
- job.payload_object.method.should == :tell
95
- job.payload_object.args.should == []
96
- job.payload_object.perform.should == 'Once upon...'
19
+ lambda { Object.send_later(:to_s) }.should change { Delayed::Job.count }.by(1)
97
20
  end
98
21
 
99
- it "should store arguments as string if they an active record" do
100
-
101
- story = Story.create :text => 'Once upon...'
102
-
103
- reader = StoryReader.new
104
- reader.send_later(:read, story)
105
-
106
- job = Delayed::Job.find(:first)
107
- job.payload_object.class.should == Delayed::PerformableMethod
108
- job.payload_object.method.should == :read
109
- job.payload_object.args.should == ["AR:Story:#{story.id}"]
110
- job.payload_object.perform.should == 'Epilog: Once upon...'
111
- end
112
-
113
22
  it "should call send later on methods which are wrapped with handle_asynchronously" do
114
23
  story = Story.create :text => 'Once upon...'
115
24
 
@@ -118,7 +27,7 @@ describe 'random ruby objects' do
118
27
  story.whatever(1, 5)
119
28
 
120
29
  Delayed::Job.count.should == 1
121
- job = Delayed::Job.find(:first)
30
+ job = Delayed::Job.first
122
31
  job.payload_object.class.should == Delayed::PerformableMethod
123
32
  job.payload_object.method.should == :whatever_without_send_later
124
33
  job.payload_object.args.should == [1, 5]
@@ -133,9 +42,9 @@ describe 'random ruby objects' do
133
42
  end
134
43
 
135
44
  it "should schedule the job in the future" do
136
- time = 1.hour.from_now
45
+ time = 1.hour.from_now.utc.to_time
137
46
  job = "string".send_at(time, :length)
138
- job.run_at.should == time
47
+ job.run_at.to_i.should == time.to_i
139
48
  end
140
49
 
141
50
  it "should store payload as PerformableMethod" do
@@ -0,0 +1,42 @@
1
+ require 'spec_helper'
2
+
3
+ class StoryReader
4
+ def read(story)
5
+ "Epilog: #{story.tell}"
6
+ end
7
+ end
8
+
9
+ describe Delayed::PerformableMethod do
10
+
11
+ it "should ignore ActiveRecord::RecordNotFound errors because they are permanent" do
12
+ story = Story.create :text => 'Once upon...'
13
+ p = Delayed::PerformableMethod.new(story, :tell, [])
14
+ story.destroy
15
+ lambda { p.perform }.should_not raise_error
16
+ end
17
+
18
+ it "should store the object as string if its an active record" do
19
+ story = Story.create :text => 'Once upon...'
20
+ p = Delayed::PerformableMethod.new(story, :tell, [])
21
+ p.class.should == Delayed::PerformableMethod
22
+ p.object.should == "LOAD;Story;#{story.id}"
23
+ p.method.should == :tell
24
+ p.args.should == []
25
+ p.perform.should == 'Once upon...'
26
+ end
27
+
28
+ it "should allow class methods to be called on ActiveRecord models" do
29
+ p = Delayed::PerformableMethod.new(Story, :count, [])
30
+ lambda { p.send(:load, p.object) }.should_not raise_error
31
+ end
32
+
33
+ it "should store arguments as string if they are active record objects" do
34
+ story = Story.create :text => 'Once upon...'
35
+ reader = StoryReader.new
36
+ p = Delayed::PerformableMethod.new(reader, :read, [story])
37
+ p.class.should == Delayed::PerformableMethod
38
+ p.method.should == :read
39
+ p.args.should == ["LOAD;Story;#{story.id}"]
40
+ p.perform.should == 'Epilog: Once upon...'
41
+ end
42
+ end
@@ -0,0 +1,21 @@
1
+ class SimpleJob
2
+ cattr_accessor :runs; self.runs = 0
3
+ def perform; @@runs += 1; end
4
+ end
5
+
6
+ class ErrorJob
7
+ cattr_accessor :runs; self.runs = 0
8
+ def perform; raise 'did not work'; end
9
+ end
10
+
11
+ class LongRunningJob
12
+ def perform; sleep 250; end
13
+ end
14
+
15
+ module M
16
+ class ModuleJob
17
+ cattr_accessor :runs; self.runs = 0
18
+ def perform; @@runs += 1; end
19
+ end
20
+
21
+ end
@@ -1,39 +1,29 @@
1
- $:.unshift(File.dirname(__FILE__) + '/../lib')
2
- $:.unshift(File.dirname(__FILE__) + '/../../rspec/lib')
3
-
4
- require 'rubygems'
5
1
  require 'active_record'
6
- gem 'sqlite3-ruby'
7
2
 
8
- require File.dirname(__FILE__) + '/../init'
9
- require 'spec'
10
-
11
- ActiveRecord::Base.logger = Logger.new('/tmp/dj.log')
12
- ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => '/tmp/jobs.sqlite')
3
+ ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
4
+ ActiveRecord::Base.logger = Delayed::Worker.logger
13
5
  ActiveRecord::Migration.verbose = false
14
- ActiveRecord::Base.default_timezone = :utc if Time.zone.nil?
15
6
 
16
7
  ActiveRecord::Schema.define do
17
-
18
8
  create_table :delayed_jobs, :force => true do |table|
19
9
  table.integer :priority, :default => 0
20
10
  table.integer :attempts, :default => 0
21
11
  table.text :handler
22
- table.string :last_error
12
+ table.text :last_error
23
13
  table.datetime :run_at
24
14
  table.datetime :locked_at
25
- table.string :locked_by
26
15
  table.datetime :failed_at
16
+ table.string :locked_by
27
17
  table.timestamps
28
18
  end
29
19
 
20
+ add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'
21
+
30
22
  create_table :stories, :force => true do |table|
31
23
  table.string :text
32
24
  end
33
-
34
25
  end
35
26
 
36
-
37
27
  # Purely useful for test cases...
38
28
  class Story < ActiveRecord::Base
39
29
  def tell; text; end
@@ -0,0 +1,6 @@
1
+ require 'dm-core'
2
+ require 'delayed/backend/data_mapper'
3
+
4
+ DataMapper.logger = Delayed::Worker.logger
5
+ DataMapper.setup(:default, "sqlite3::memory:")
6
+ DataMapper.auto_migrate!
@@ -0,0 +1,15 @@
1
+ require 'mongo_mapper'
2
+
3
+ MongoMapper.connection = Mongo::Connection.new nil, nil, :logger => Delayed::Worker.logger
4
+ MongoMapper.database = 'delayed_job'
5
+
6
+ unless defined?(Story)
7
+ class Story
8
+ include ::MongoMapper::Document
9
+ def tell; text; end
10
+ def whatever(n, _); tell*n; end
11
+ def self.count; end
12
+
13
+ handle_asynchronously :whatever
14
+ end
15
+ end
@@ -0,0 +1,25 @@
1
+ $:.unshift(File.dirname(__FILE__) + '/../lib')
2
+
3
+ require 'rubygems'
4
+ require 'spec'
5
+ require 'logger'
6
+
7
+ require 'delayed_job'
8
+ require 'sample_jobs'
9
+
10
+ Delayed::Worker.logger = Logger.new('/tmp/dj.log')
11
+
12
+ # determine the available backends
13
+ BACKENDS = []
14
+ Dir.glob("#{File.dirname(__FILE__)}/setup/*.rb") do |backend|
15
+ begin
16
+ backend = File.basename(backend, '.rb')
17
+ require "setup/#{backend}"
18
+ require "backend/#{backend}_job_spec"
19
+ BACKENDS << backend.to_sym
20
+ rescue LoadError
21
+ puts "Unable to load #{backend} backend! #{$!}"
22
+ end
23
+ end
24
+
25
+ Delayed::Worker.backend = BACKENDS.first
data/spec/story_spec.rb CHANGED
@@ -1,4 +1,4 @@
1
- require File.dirname(__FILE__) + '/database'
1
+ require 'spec_helper'
2
2
 
3
3
  describe "A story" do
4
4