raj_delayed_job_active_record 0.0.2 → 0.0.3

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.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND
17
+ NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,115 @@
1
+ require 'active_record'
2
+ require 'active_record/version'
3
+ module Delayed
4
+ module Backend
5
+ module ActiveRecord
6
+ # A job object that is persisted to the database.
7
+ # Contains the work object as a YAML field.
8
+ class Job < ::ActiveRecord::Base
9
+ include Delayed::Backend::Base
10
+
11
+ attr_accessible :priority, :run_at, :queue, :payload_object,
12
+ :failed_at, :locked_at, :locked_by
13
+
14
+ before_save :set_default_run_at
15
+
16
+ def self.rails3?
17
+ ::ActiveRecord::VERSION::MAJOR == 3
18
+ end
19
+
20
+ if rails3?
21
+ self.table_name = 'delayed_jobs'
22
+ scope :ready_to_run, lambda{|worker_name, max_run_time|
23
+ where('(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', db_time_now, db_time_now - max_run_time, worker_name)
24
+ }
25
+ scope :by_priority, order('priority ASC, run_at ASC')
26
+ else
27
+ set_table_name :delayed_jobs
28
+ named_scope :ready_to_run, lambda {|worker_name, max_run_time|
29
+ { :conditions => ['(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', db_time_now, db_time_now - max_run_time, worker_name] }
30
+ }
31
+ named_scope :by_priority, :order => 'priority ASC, run_at ASC'
32
+ end
33
+
34
+ def self.before_fork
35
+ ::ActiveRecord::Base.clear_all_connections!
36
+ end
37
+
38
+ def self.after_fork
39
+ ::ActiveRecord::Base.establish_connection
40
+ end
41
+
42
+ # When a worker is exiting, make sure we don't have any locked jobs.
43
+ def self.clear_locks!(worker_name)
44
+ update_all("locked_by = null, locked_at = null", ["locked_by = ?", worker_name])
45
+ end
46
+
47
+ # Find a few candidate jobs to run (in case some immediately get locked by others).
48
+ def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time)
49
+ begin
50
+ scope = self.ready_to_run(worker_name, max_run_time)
51
+ scope = scope.scoped(:conditions => ['priority >= ?', Worker.min_priority]) if Worker.min_priority
52
+ scope = scope.scoped(:conditions => ['priority <= ?', Worker.max_priority]) if Worker.max_priority
53
+ scope = scope.scoped(:conditions => ["queue IN (?)", Worker.queues]) if Worker.queues.any?
54
+
55
+ ::ActiveRecord::Base.silence do
56
+ scope.by_priority.all(:limit => limit)
57
+ end
58
+
59
+ rescue => ex
60
+ puts "ddddddddddddddddddddddddddddddddd"
61
+
62
+ puts ex.message
63
+ puts "ddddddddddddddddddddddddddddddddd"
64
+ if (ex.message =~ /mysql/i) || (ex.message =~ /server has gone away/i)
65
+ Rails.logger.info ex
66
+ establish_connection
67
+ retry
68
+ end
69
+ end
70
+ end
71
+
72
+ # Lock this job for this worker.
73
+ # Returns true if we have the lock, false otherwise.
74
+ def lock_exclusively!(max_run_time, worker)
75
+ now = self.class.db_time_now
76
+ affected_rows = if locked_by != worker
77
+ # We don't own this job so we will update the locked_by name and the locked_at
78
+ self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?) and (run_at <= ?)", id, (now - max_run_time.to_i), now])
79
+ else
80
+ # We already own this job, this may happen if the job queue crashes.
81
+ # Simply resume and update the locked_at
82
+ self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker])
83
+ end
84
+ if affected_rows == 1
85
+ self.locked_at = now
86
+ self.locked_by = worker
87
+ self.locked_at_will_change!
88
+ self.locked_by_will_change!
89
+ return true
90
+ else
91
+ return false
92
+ end
93
+ end
94
+
95
+ # Get the current time (GMT or local depending on DB)
96
+ # Note: This does not ping the DB to get the time, so all your clients
97
+ # must have syncronized clocks.
98
+ def self.db_time_now
99
+ if Time.zone
100
+ Time.zone.now
101
+ elsif ::ActiveRecord::Base.default_timezone == :utc
102
+ Time.now.utc
103
+ else
104
+ Time.now
105
+ end
106
+ end
107
+
108
+ def reload(*args)
109
+ reset
110
+ super
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,17 @@
1
+ require 'generators/delayed_job/delayed_job_generator'
2
+ require 'rails/generators/migration'
3
+ require 'rails/generators/active_record/migration'
4
+
5
+ # Extend the DelayedJobGenerator so that it creates an AR migration
6
+ module DelayedJob
7
+ class ActiveRecordGenerator < ::DelayedJobGenerator
8
+ include Rails::Generators::Migration
9
+ extend ActiveRecord::Generators::Migration
10
+
11
+ self.source_paths << File.join(File.dirname(__FILE__), 'templates')
12
+
13
+ def create_migration_file
14
+ migration_template 'migration.rb', 'db/migrate/create_delayed_jobs.rb'
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,22 @@
1
+ class CreateDelayedJobs < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :delayed_jobs, :force => true do |table|
4
+ table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue
5
+ table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually.
6
+ table.text :handler # YAML-encoded string of the object that will do work
7
+ table.text :last_error # reason for last failure (See Note below)
8
+ table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
9
+ table.datetime :locked_at # Set when a client is working on this object
10
+ table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
11
+ table.string :locked_by # Who is working on this object (if locked)
12
+ table.string :queue # The name of the queue this job is in
13
+ table.timestamps
14
+ end
15
+
16
+ add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'
17
+ end
18
+
19
+ def self.down
20
+ drop_table :delayed_jobs
21
+ end
22
+ end
@@ -0,0 +1,9 @@
1
+ class AddQueueToDelayedJobs < ActiveRecord::Migration
2
+ def self.up
3
+ add_column :delayed_jobs, :queue, :string
4
+ end
5
+
6
+ def self.down
7
+ remove_column :delayed_jobs, :queue
8
+ end
9
+ end
@@ -0,0 +1,17 @@
1
+ require 'generators/delayed_job/delayed_job_generator'
2
+ require 'rails/generators/migration'
3
+ require 'rails/generators/active_record/migration'
4
+
5
+ # Extend the DelayedJobGenerator so that it creates an AR migration
6
+ module DelayedJob
7
+ class UpgradeGenerator < ::DelayedJobGenerator
8
+ include Rails::Generators::Migration
9
+ extend ActiveRecord::Generators::Migration
10
+
11
+ self.source_paths << File.join(File.dirname(__FILE__), 'templates')
12
+
13
+ def create_migration_file
14
+ migration_template 'upgrade_migration.rb', 'db/migrate/add_queue_to_delayed_jobs.rb'
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,5 @@
1
+ require 'active_record'
2
+ require 'delayed_job'
3
+ require 'delayed/backend/active_record'
4
+
5
+ Delayed::Worker.backend = :active_record
data/spec/database.yml ADDED
@@ -0,0 +1,8 @@
1
+ sqlite:
2
+ adapter: sqlite3
3
+ database: ":memory:"
4
+
5
+ mysql:
6
+ adapter: mysql
7
+ database: delayed_job
8
+ uesrname: root
@@ -0,0 +1,59 @@
1
+ require 'spec_helper'
2
+ require 'delayed/backend/active_record'
3
+
4
+ describe Delayed::Backend::ActiveRecord::Job do
5
+ after do
6
+ Time.zone = nil
7
+ end
8
+
9
+ it_should_behave_like 'a delayed_job backend'
10
+
11
+ context "db_time_now" do
12
+ it "should return time in current time zone if set" do
13
+ Time.zone = 'Eastern Time (US & Canada)'
14
+ %w(EST EDT).should include(Delayed::Job.db_time_now.zone)
15
+ end
16
+
17
+ it "should return UTC time if that is the AR default" do
18
+ Time.zone = nil
19
+ ActiveRecord::Base.default_timezone = :utc
20
+ Delayed::Backend::ActiveRecord::Job.db_time_now.zone.should == 'UTC'
21
+ end
22
+
23
+ it "should return local time if that is the AR default" do
24
+ Time.zone = 'Central Time (US & Canada)'
25
+ ActiveRecord::Base.default_timezone = :local
26
+ %w(CST CDT).should include(Delayed::Backend::ActiveRecord::Job.db_time_now.zone)
27
+ end
28
+ end
29
+
30
+ describe "after_fork" do
31
+ it "should call reconnect on the connection" do
32
+ ActiveRecord::Base.should_receive(:establish_connection)
33
+ Delayed::Backend::ActiveRecord::Job.after_fork
34
+ end
35
+ end
36
+
37
+ describe "enqueue" do
38
+ it "should allow enqueue hook to modify job at DB level" do
39
+ later = described_class.db_time_now + 20.minutes
40
+ job = Delayed::Backend::ActiveRecord::Job.enqueue :payload_object => EnqueueJobMod.new
41
+ Delayed::Backend::ActiveRecord::Job.find(job.id).run_at.should be_within(1).of(later)
42
+ end
43
+ end
44
+
45
+ context "ActiveRecord::Base.send(:attr_accessible, nil)" do
46
+ before do
47
+ Delayed::Backend::ActiveRecord::Job.send(:attr_accessible, nil)
48
+ end
49
+
50
+ after do
51
+ Delayed::Backend::ActiveRecord::Job.send(:attr_accessible, *Delayed::Backend::ActiveRecord::Job.new.attributes.keys)
52
+ end
53
+
54
+ it "should still be accessible" do
55
+ job = Delayed::Backend::ActiveRecord::Job.enqueue :payload_object => EnqueueJobMod.new
56
+ Delayed::Backend::ActiveRecord::Job.find(job.id).handler.should_not be_blank
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,15 @@
1
+ require 'spec_helper'
2
+
3
+ describe ActiveRecord do
4
+ it 'should load classes with non-default primary key' do
5
+ lambda {
6
+ YAML.load(Story.create.to_yaml)
7
+ }.should_not raise_error
8
+ end
9
+
10
+ it 'should load classes even if not in default scope' do
11
+ lambda {
12
+ YAML.load(Story.create(:scoped => false).to_yaml)
13
+ }.should_not raise_error
14
+ end
15
+ end
@@ -0,0 +1,52 @@
1
+ $:.unshift(File.dirname(__FILE__) + '/../lib')
2
+
3
+ require 'rubygems'
4
+ require 'bundler/setup'
5
+ require 'rspec'
6
+ require 'logger'
7
+
8
+ require 'delayed_job_active_record'
9
+ require 'delayed/backend/shared_spec'
10
+
11
+ Delayed::Worker.logger = Logger.new('/tmp/dj.log')
12
+ ENV['RAILS_ENV'] = 'test'
13
+
14
+ config = YAML.load(File.read('spec/database.yml'))
15
+ ActiveRecord::Base.establish_connection config['sqlite']
16
+ ActiveRecord::Base.logger = Delayed::Worker.logger
17
+ ActiveRecord::Migration.verbose = false
18
+
19
+ ActiveRecord::Schema.define do
20
+ create_table :delayed_jobs, :force => true do |table|
21
+ table.integer :priority, :default => 0
22
+ table.integer :attempts, :default => 0
23
+ table.text :handler
24
+ table.text :last_error
25
+ table.datetime :run_at
26
+ table.datetime :locked_at
27
+ table.datetime :failed_at
28
+ table.string :locked_by
29
+ table.string :queue
30
+ table.timestamps
31
+ end
32
+
33
+ add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'
34
+
35
+ create_table :stories, :primary_key => :story_id, :force => true do |table|
36
+ table.string :text
37
+ table.boolean :scoped, :default => true
38
+ end
39
+ end
40
+
41
+ # Purely useful for test cases...
42
+ class Story < ActiveRecord::Base
43
+ set_primary_key :story_id
44
+ def tell; text; end
45
+ def whatever(n, _); tell*n; end
46
+ default_scope where(:scoped => true)
47
+
48
+ handle_asynchronously :whatever
49
+ end
50
+
51
+ # Add this directory so the ActiveSupport autoloading works
52
+ ActiveSupport::Dependencies.autoload_paths << File.dirname(__FILE__)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: raj_delayed_job_active_record
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.2
4
+ version: 0.0.3
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -99,6 +99,17 @@ extensions: []
99
99
  extra_rdoc_files:
100
100
  - README.md
101
101
  files:
102
+ - lib/raj_delayed_job_active_record.rb
103
+ - lib/generators/delayed_job/upgrade_generator.rb
104
+ - lib/generators/delayed_job/templates/migration.rb
105
+ - lib/generators/delayed_job/templates/upgrade_migration.rb
106
+ - lib/generators/delayed_job/active_record_generator.rb
107
+ - lib/delayed/backend/active_record.rb
108
+ - spec/delayed/backend/active_record_spec.rb
109
+ - spec/delayed/serialization/active_record_spec.rb
110
+ - spec/spec_helper.rb
111
+ - spec/database.yml
112
+ - LICENSE
102
113
  - README.md
103
114
  homepage: http://github.com/rajeshgarg/raj_delayed_job_active_record
104
115
  licenses: