diff options
Diffstat (limited to 'activejob/lib/active_job')
31 files changed, 592 insertions, 289 deletions
diff --git a/activejob/lib/active_job/arguments.rb b/activejob/lib/active_job/arguments.rb index a5c749e5e7..de11e7fcb1 100644 --- a/activejob/lib/active_job/arguments.rb +++ b/activejob/lib/active_job/arguments.rb @@ -1,26 +1,16 @@ -require 'active_support/core_ext/hash' +# frozen_string_literal: true + +require "active_support/core_ext/hash" module ActiveJob # Raised when an exception is raised during job arguments deserialization. # # Wraps the original exception raised as +cause+. class DeserializationError < StandardError - def initialize(e = nil) #:nodoc: - if e - ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \ - "Exceptions will automatically capture the original exception.", caller) - end - + def initialize #:nodoc: super("Error while trying to deserialize arguments: #{$!.message}") set_backtrace $!.backtrace end - - # The original exception that was raised during deserialization of job - # arguments. - def original_exception - ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller) - cause - end end # Raised when an unsupported argument type is set as a job argument. We @@ -34,8 +24,8 @@ module ActiveJob module Arguments extend self # :nodoc: - # Calls #uniq since Integer, Fixnum, and Bignum are all the same class on Ruby 2.4+ - TYPE_WHITELIST = [ NilClass, String, Integer, Fixnum, Bignum, Float, BigDecimal, TrueClass, FalseClass ].uniq + TYPE_WHITELIST = [ NilClass, String, Integer, Float, BigDecimal, TrueClass, FalseClass ] + TYPE_WHITELIST.push(Fixnum, Bignum) unless 1.class == Integer # Serializes a set of arguments. Whitelisted types are returned # as-is. Arrays/Hashes are serialized element by element. @@ -55,11 +45,11 @@ module ActiveJob private # :nodoc: - GLOBALID_KEY = '_aj_globalid'.freeze + GLOBALID_KEY = "_aj_globalid".freeze # :nodoc: - SYMBOL_KEYS_KEY = '_aj_symbol_keys'.freeze + SYMBOL_KEYS_KEY = "_aj_symbol_keys".freeze # :nodoc: - WITH_INDIFFERENT_ACCESS_KEY = '_aj_hash_with_indifferent_access'.freeze + WITH_INDIFFERENT_ACCESS_KEY = "_aj_hash_with_indifferent_access".freeze private_constant :GLOBALID_KEY, :SYMBOL_KEYS_KEY, :WITH_INDIFFERENT_ACCESS_KEY def serialize_argument(argument) @@ -104,7 +94,7 @@ module ActiveJob end def serialized_global_id?(hash) - hash.size == 1 and hash.include?(GLOBALID_KEY) + hash.size == 1 && hash.include?(GLOBALID_KEY) end def deserialize_global_id(hash) diff --git a/activejob/lib/active_job/base.rb b/activejob/lib/active_job/base.rb index ff5c69ddc6..ae112abb2c 100644 --- a/activejob/lib/active_job/base.rb +++ b/activejob/lib/active_job/base.rb @@ -1,12 +1,15 @@ -require 'active_job/core' -require 'active_job/queue_adapter' -require 'active_job/queue_name' -require 'active_job/queue_priority' -require 'active_job/enqueuing' -require 'active_job/execution' -require 'active_job/callbacks' -require 'active_job/logging' -require 'active_job/translation' +# frozen_string_literal: true + +require "active_job/core" +require "active_job/queue_adapter" +require "active_job/queue_name" +require "active_job/queue_priority" +require "active_job/enqueuing" +require "active_job/execution" +require "active_job/callbacks" +require "active_job/exceptions" +require "active_job/logging" +require "active_job/translation" module ActiveJob #:nodoc: # = Active Job @@ -62,6 +65,7 @@ module ActiveJob #:nodoc: include Enqueuing include Execution include Callbacks + include Exceptions include Logging include Translation diff --git a/activejob/lib/active_job/callbacks.rb b/activejob/lib/active_job/callbacks.rb index b206522a60..334b24fb3b 100644 --- a/activejob/lib/active_job/callbacks.rb +++ b/activejob/lib/active_job/callbacks.rb @@ -1,10 +1,12 @@ -require 'active_support/callbacks' +# frozen_string_literal: true + +require "active_support/callbacks" module ActiveJob # = Active Job Callbacks # # Active Job provides hooks during the life cycle of a job. Callbacks allow you - # to trigger logic during the life cycle of a job. Available callbacks are: + # to trigger logic during this cycle. Available callbacks are: # # * <tt>before_enqueue</tt> # * <tt>around_enqueue</tt> @@ -13,6 +15,8 @@ module ActiveJob # * <tt>around_perform</tt> # * <tt>after_perform</tt> # + # NOTE: Calling the same callback multiple times will overwrite previous callback definitions. + # module Callbacks extend ActiveSupport::Concern include ActiveSupport::Callbacks diff --git a/activejob/lib/active_job/configured_job.rb b/activejob/lib/active_job/configured_job.rb index 979280b910..67daf48b36 100644 --- a/activejob/lib/active_job/configured_job.rb +++ b/activejob/lib/active_job/configured_job.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + module ActiveJob class ConfiguredJob #:nodoc: - def initialize(job_class, options={}) + def initialize(job_class, options = {}) @options = options @job_class = job_class end diff --git a/activejob/lib/active_job/core.rb b/activejob/lib/active_job/core.rb index f7f882c998..879746fc01 100644 --- a/activejob/lib/active_job/core.rb +++ b/activejob/lib/active_job/core.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob # Provides general behavior that will be included into every Active Job # object that inherits from ActiveJob::Base. @@ -24,6 +26,9 @@ module ActiveJob # ID optionally provided by adapter attr_accessor :provider_job_id + # Number of times this job has been executed (which increments on every retry, like after an exception). + attr_accessor :executions + # I18n.locale to be used during the job. attr_accessor :locale end @@ -33,7 +38,7 @@ module ActiveJob module ClassMethods # Creates a new job instance from a hash created with +serialize+ def deserialize(job_data) - job = job_data['job_class'].constantize.new + job = job_data["job_class"].constantize.new job.deserialize(job_data) job end @@ -56,7 +61,7 @@ module ActiveJob # VideoJob.set(queue: :some_queue, wait: 5.minutes).perform_later(Video.last) # VideoJob.set(queue: :some_queue, wait_until: Time.now.tomorrow).perform_later(Video.last) # VideoJob.set(queue: :some_queue, wait: 5.minutes, priority: 10).perform_later(Video.last) - def set(options={}) + def set(options = {}) ConfiguredJob.new(self, options) end end @@ -68,18 +73,21 @@ module ActiveJob @job_id = SecureRandom.uuid @queue_name = self.class.queue_name @priority = self.class.priority + @executions = 0 end # Returns a hash with the job data that can safely be passed to the # queueing adapter. def serialize { - 'job_class' => self.class.name, - 'job_id' => job_id, - 'queue_name' => queue_name, - 'priority' => priority, - 'arguments' => serialize_arguments(arguments), - 'locale' => I18n.locale.to_s + "job_class" => self.class.name, + "job_id" => job_id, + "provider_job_id" => provider_job_id, + "queue_name" => queue_name, + "priority" => priority, + "arguments" => serialize_arguments(arguments), + "executions" => executions, + "locale" => I18n.locale.to_s } end @@ -89,26 +97,34 @@ module ActiveJob # ==== Examples # # class DeliverWebhookJob < ActiveJob::Base + # attr_writer :attempt_number + # + # def attempt_number + # @attempt_number ||= 0 + # end + # # def serialize - # super.merge('attempt_number' => (@attempt_number || 0) + 1) + # super.merge('attempt_number' => attempt_number + 1) # end # # def deserialize(job_data) # super - # @attempt_number = job_data['attempt_number'] + # self.attempt_number = job_data['attempt_number'] # end # - # rescue_from(TimeoutError) do |exception| - # raise exception if @attempt_number > 5 + # rescue_from(Timeout::Error) do |exception| + # raise exception if attempt_number > 5 # retry_job(wait: 10) # end # end def deserialize(job_data) - self.job_id = job_data['job_id'] - self.queue_name = job_data['queue_name'] - self.priority = job_data['priority'] - self.serialized_arguments = job_data['arguments'] - self.locale = job_data['locale'] || I18n.locale.to_s + self.job_id = job_data["job_id"] + self.provider_job_id = job_data["provider_job_id"] + self.queue_name = job_data["queue_name"] + self.priority = job_data["priority"] + self.serialized_arguments = job_data["arguments"] + self.executions = job_data["executions"] + self.locale = job_data["locale"] || I18n.locale.to_s end private diff --git a/activejob/lib/active_job/enqueuing.rb b/activejob/lib/active_job/enqueuing.rb index 9dc3c0fa57..53cb98fc71 100644 --- a/activejob/lib/active_job/enqueuing.rb +++ b/activejob/lib/active_job/enqueuing.rb @@ -1,14 +1,16 @@ -require 'active_job/arguments' +# frozen_string_literal: true + +require "active_job/arguments" module ActiveJob - # Provides behavior for enqueuing and retrying jobs. + # Provides behavior for enqueuing jobs. module Enqueuing extend ActiveSupport::Concern # Includes the +perform_later+ method for job initialization. module ClassMethods # Push a job onto the queue. The arguments must be legal JSON types - # (string, int, float, nil, true, false, hash or array) or + # (+string+, +int+, +float+, +nil+, +true+, +false+, +hash+ or +array+) or # GlobalID::Identification instances. Arbitrary Ruby objects # are not supported. # @@ -18,37 +20,12 @@ module ActiveJob job_or_instantiate(*args).enqueue end - protected - def job_or_instantiate(*args) + private + def job_or_instantiate(*args) # :doc: args.first.is_a?(self) ? args.first : new(*args) end end - # Reschedules the job to be re-executed. This is useful in combination - # with the +rescue_from+ option. When you rescue an exception from your job - # you can ask Active Job to retry performing your job. - # - # ==== Options - # * <tt>:wait</tt> - Enqueues the job with the specified delay - # * <tt>:wait_until</tt> - Enqueues the job at the time specified - # * <tt>:queue</tt> - Enqueues the job on the specified queue - # * <tt>:priority</tt> - Enqueues the job with the specified priority - # - # ==== Examples - # - # class SiteScraperJob < ActiveJob::Base - # rescue_from(ErrorLoadingSite) do - # retry_job queue: :low_priority - # end - # - # def perform(*args) - # # raise ErrorLoadingSite if cannot scrape - # end - # end - def retry_job(options={}) - enqueue options - end - # Enqueues the job to be performed by the queue adapter. # # ==== Options @@ -64,14 +41,14 @@ module ActiveJob # my_job_instance.enqueue queue: :important # my_job_instance.enqueue wait_until: Date.tomorrow.midnight # my_job_instance.enqueue priority: 10 - def enqueue(options={}) + def enqueue(options = {}) self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait] self.scheduled_at = options[:wait_until].to_f if options[:wait_until] self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue] self.priority = options[:priority].to_i if options[:priority] run_callbacks :enqueue do - if self.scheduled_at - self.class.queue_adapter.enqueue_at self, self.scheduled_at + if scheduled_at + self.class.queue_adapter.enqueue_at self, scheduled_at else self.class.queue_adapter.enqueue self end diff --git a/activejob/lib/active_job/exceptions.rb b/activejob/lib/active_job/exceptions.rb new file mode 100644 index 0000000000..8b4a88ba6a --- /dev/null +++ b/activejob/lib/active_job/exceptions.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require "active_support/core_ext/numeric/time" + +module ActiveJob + # Provides behavior for retrying and discarding jobs on exceptions. + module Exceptions + extend ActiveSupport::Concern + + module ClassMethods + # Catch the exception and reschedule job for re-execution after so many seconds, for a specific number of attempts. + # If the exception keeps getting raised beyond the specified number of attempts, the exception is allowed to + # bubble up to the underlying queuing system, which may have its own retry mechanism or place it in a + # holding queue for inspection. + # + # You can also pass a block that'll be invoked if the retry attempts fail for custom logic rather than letting + # the exception bubble up. This block is yielded with the job instance as the first and the error instance as the second parameter. + # + # ==== Options + # * <tt>:wait</tt> - Re-enqueues the job with a delay specified either in seconds (default: 3 seconds), + # as a computing proc that the number of executions so far as an argument, or as a symbol reference of + # <tt>:exponentially_longer</tt>, which applies the wait algorithm of <tt>(executions ** 4) + 2</tt> + # (first wait 3s, then 18s, then 83s, etc) + # * <tt>:attempts</tt> - Re-enqueues the job the specified number of times (default: 5 attempts) + # * <tt>:queue</tt> - Re-enqueues the job on a different queue + # * <tt>:priority</tt> - Re-enqueues the job with a different priority + # + # ==== Examples + # + # class RemoteServiceJob < ActiveJob::Base + # retry_on CustomAppException # defaults to 3s wait, 5 attempts + # retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 } + # retry_on(YetAnotherCustomAppException) do |job, exception| + # ExceptionNotifier.caught(exception) + # end + # retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3 + # retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10 + # + # def perform(*args) + # # Might raise CustomAppException, AnotherCustomAppException, or YetAnotherCustomAppException for something domain specific + # # Might raise ActiveRecord::Deadlocked when a local db deadlock is detected + # # Might raise Net::OpenTimeout when the remote service is down + # end + # end + def retry_on(exception, wait: 3.seconds, attempts: 5, queue: nil, priority: nil) + rescue_from exception do |error| + if executions < attempts + logger.error "Retrying #{self.class} in #{wait} seconds, due to a #{exception}. The original exception was #{error.cause.inspect}." + retry_job wait: determine_delay(wait), queue: queue, priority: priority + else + if block_given? + yield self, error + else + logger.error "Stopped retrying #{self.class} due to a #{exception}, which reoccurred on #{executions} attempts. The original exception was #{error.cause.inspect}." + raise error + end + end + end + end + + # Discard the job with no attempts to retry, if the exception is raised. This is useful when the subject of the job, + # like an Active Record, is no longer available, and the job is thus no longer relevant. + # + # ==== Example + # + # class SearchIndexingJob < ActiveJob::Base + # discard_on ActiveJob::DeserializationError + # + # def perform(record) + # # Will raise ActiveJob::DeserializationError if the record can't be deserialized + # end + # end + def discard_on(exception) + rescue_from exception do |error| + logger.error "Discarded #{self.class} due to a #{exception}. The original exception was #{error.cause.inspect}." + end + end + end + + # Reschedules the job to be re-executed. This is useful in combination + # with the +rescue_from+ option. When you rescue an exception from your job + # you can ask Active Job to retry performing your job. + # + # ==== Options + # * <tt>:wait</tt> - Enqueues the job with the specified delay in seconds + # * <tt>:wait_until</tt> - Enqueues the job at the time specified + # * <tt>:queue</tt> - Enqueues the job on the specified queue + # * <tt>:priority</tt> - Enqueues the job with the specified priority + # + # ==== Examples + # + # class SiteScraperJob < ActiveJob::Base + # rescue_from(ErrorLoadingSite) do + # retry_job queue: :low_priority + # end + # + # def perform(*args) + # # raise ErrorLoadingSite if cannot scrape + # end + # end + def retry_job(options = {}) + enqueue options + end + + private + def determine_delay(seconds_or_duration_or_algorithm) + case seconds_or_duration_or_algorithm + when :exponentially_longer + (executions**4) + 2 + when ActiveSupport::Duration + duration = seconds_or_duration_or_algorithm + duration.to_i + when Integer + seconds = seconds_or_duration_or_algorithm + seconds + when Proc + algorithm = seconds_or_duration_or_algorithm + algorithm.call(executions) + else + raise "Couldn't determine a delay based on #{seconds_or_duration_or_algorithm.inspect}" + end + end + end +end diff --git a/activejob/lib/active_job/execution.rb b/activejob/lib/active_job/execution.rb index 4e4acfc2c2..d75be376ec 100644 --- a/activejob/lib/active_job/execution.rb +++ b/activejob/lib/active_job/execution.rb @@ -1,5 +1,7 @@ -require 'active_support/rescuable' -require 'active_job/arguments' +# frozen_string_literal: true + +require "active_support/rescuable" +require "active_job/arguments" module ActiveJob module Execution @@ -31,6 +33,9 @@ module ActiveJob def perform_now deserialize_arguments_if_needed run_callbacks :perform do + # Guard against jobs that were persisted before we started counting executions by zeroing out nil counters + self.executions = (executions || 0) + 1 + perform(*arguments) end rescue => exception diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb index 0d50c27938..49dfd4095e 100644 --- a/activejob/lib/active_job/gem_version.rb +++ b/activejob/lib/active_job/gem_version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob # Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt> def self.gem_version @@ -6,9 +8,9 @@ module ActiveJob module VERSION MAJOR = 5 - MINOR = 1 + MINOR = 2 TINY = 0 - PRE = "alpha" + PRE = "beta2" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb index d5c7920131..f53b7eaee5 100644 --- a/activejob/lib/active_job/logging.rb +++ b/activejob/lib/active_job/logging.rb @@ -1,14 +1,16 @@ -require 'active_support/core_ext/hash/transform_values' -require 'active_support/core_ext/string/filters' -require 'active_support/tagged_logging' -require 'active_support/logger' +# frozen_string_literal: true + +require "active_support/core_ext/hash/transform_values" +require "active_support/core_ext/string/filters" +require "active_support/tagged_logging" +require "active_support/logger" module ActiveJob module Logging #:nodoc: extend ActiveSupport::Concern included do - cattr_accessor(:logger) { ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) } + cattr_accessor :logger, default: ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) around_enqueue do |_, block, _| tag_logger do @@ -18,7 +20,7 @@ module ActiveJob around_perform do |job, block, _| tag_logger(job.class.name, job.job_id) do - payload = {adapter: job.class.queue_adapter, job: job} + payload = { adapter: job.class.queue_adapter, job: job } ActiveSupport::Notifications.instrument("perform_start.active_job", payload.dup) ActiveSupport::Notifications.instrument("perform.active_job", payload) do block.call @@ -41,7 +43,7 @@ module ActiveJob def tag_logger(*tags) if logger.respond_to?(:tagged) tags.unshift "ActiveJob" unless logger_tagged_by_active_job? - logger.tagged(*tags){ yield } + logger.tagged(*tags) { yield } else yield end @@ -51,70 +53,77 @@ module ActiveJob logger.formatter.current_tags.include?("ActiveJob") end - class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: - def enqueue(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)}" + args_info(job) + class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: + def enqueue(event) + info do + job = event.payload[:job] + "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)}" + args_info(job) + end end - end - def enqueue_at(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)} at #{scheduled_at(event)}" + args_info(job) + def enqueue_at(event) + info do + job = event.payload[:job] + "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)} at #{scheduled_at(event)}" + args_info(job) + end end - end - def perform_start(event) - info do - job = event.payload[:job] - "Performing #{job.class.name} from #{queue_name(event)}" + args_info(job) + def perform_start(event) + info do + job = event.payload[:job] + "Performing #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)}" + args_info(job) + end end - end - def perform(event) - info do + def perform(event) job = event.payload[:job] - "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2)}ms" + ex = event.payload[:exception_object] + if ex + error do + "Error performing #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)} in #{event.duration.round(2)}ms: #{ex.class} (#{ex.message}):\n" + Array(ex.backtrace).join("\n") + end + else + info do + "Performed #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)} in #{event.duration.round(2)}ms" + end + end end - end - private - def queue_name(event) - event.payload[:adapter].class.name.demodulize.remove('Adapter') + "(#{event.payload[:job].queue_name})" - end + private + def queue_name(event) + event.payload[:adapter].class.name.demodulize.remove("Adapter") + "(#{event.payload[:job].queue_name})" + end - def args_info(job) - if job.arguments.any? - ' with arguments: ' + - job.arguments.map { |arg| format(arg).inspect }.join(', ') - else - '' + def args_info(job) + if job.arguments.any? + " with arguments: " + + job.arguments.map { |arg| format(arg).inspect }.join(", ") + else + "" + end end - end - def format(arg) - case arg - when Hash - arg.transform_values { |value| format(value) } - when Array - arg.map { |value| format(value) } - when GlobalID::Identification - arg.to_global_id rescue arg - else - arg + def format(arg) + case arg + when Hash + arg.transform_values { |value| format(value) } + when Array + arg.map { |value| format(value) } + when GlobalID::Identification + arg.to_global_id rescue arg + else + arg + end end - end - def scheduled_at(event) - Time.at(event.payload[:job].scheduled_at).utc - end + def scheduled_at(event) + Time.at(event.payload[:job].scheduled_at).utc + end - def logger - ActiveJob::Base.logger - end - end + def logger + ActiveJob::Base.logger + end + end end end diff --git a/activejob/lib/active_job/queue_adapter.rb b/activejob/lib/active_job/queue_adapter.rb index 72e4ebf935..dd05800baf 100644 --- a/activejob/lib/active_job/queue_adapter.rb +++ b/activejob/lib/active_job/queue_adapter.rb @@ -1,6 +1,6 @@ -require 'active_job/queue_adapters/inline_adapter' -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/string/inflections' +# frozen_string_literal: true + +require "active_support/core_ext/string/inflections" module ActiveJob # The <tt>ActiveJob::QueueAdapter</tt> module is used to load the @@ -9,6 +9,7 @@ module ActiveJob extend ActiveSupport::Concern included do + class_attribute :_queue_adapter_name, instance_accessor: false, instance_predicate: false class_attribute :_queue_adapter, instance_accessor: false, instance_predicate: false self.queue_adapter = :async end @@ -21,43 +22,45 @@ module ActiveJob _queue_adapter end + def queue_adapter_name + _queue_adapter_name + end + # Specify the backend queue provider. The default queue adapter # is the +:async+ queue. See QueueAdapters for more # information. def queue_adapter=(name_or_adapter_or_class) - self._queue_adapter = interpret_adapter(name_or_adapter_or_class) + interpret_adapter(name_or_adapter_or_class) end private - def interpret_adapter(name_or_adapter_or_class) - case name_or_adapter_or_class - when Symbol, String - ActiveJob::QueueAdapters.lookup(name_or_adapter_or_class).new - else - if queue_adapter?(name_or_adapter_or_class) - name_or_adapter_or_class - elsif queue_adapter_class?(name_or_adapter_or_class) - ActiveSupport::Deprecation.warn "Passing an adapter class is deprecated " \ - "and will be removed in Rails 5.1. Please pass an adapter name " \ - "(.queue_adapter = :#{name_or_adapter_or_class.name.demodulize.remove('Adapter').underscore}) " \ - "or an instance (.queue_adapter = #{name_or_adapter_or_class.name}.new) instead." - name_or_adapter_or_class.new + def interpret_adapter(name_or_adapter_or_class) + case name_or_adapter_or_class + when Symbol, String + assign_adapter(name_or_adapter_or_class.to_s, + ActiveJob::QueueAdapters.lookup(name_or_adapter_or_class).new) else - raise ArgumentError + if queue_adapter?(name_or_adapter_or_class) + adapter_name = "#{name_or_adapter_or_class.class.name.demodulize.remove('Adapter').underscore}" + assign_adapter(adapter_name, + name_or_adapter_or_class) + else + raise ArgumentError + end end end - end - QUEUE_ADAPTER_METHODS = [:enqueue, :enqueue_at].freeze + def assign_adapter(adapter_name, queue_adapter) + self._queue_adapter_name = adapter_name + self._queue_adapter = queue_adapter + end - def queue_adapter?(object) - QUEUE_ADAPTER_METHODS.all? { |meth| object.respond_to?(meth) } - end + QUEUE_ADAPTER_METHODS = [:enqueue, :enqueue_at].freeze - def queue_adapter_class?(object) - object.is_a?(Class) && QUEUE_ADAPTER_METHODS.all? { |meth| object.public_method_defined?(meth) } - end + def queue_adapter?(object) + QUEUE_ADAPTER_METHODS.all? { |meth| object.respond_to?(meth) } + end end end end diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb index 71154d8785..c1a1d3c510 100644 --- a/activejob/lib/active_job/queue_adapters.rb +++ b/activejob/lib/active_job/queue_adapters.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob # == Active Job adapters # @@ -8,7 +10,7 @@ module ActiveJob # * {Qu}[https://github.com/bkeepers/qu] # * {Que}[https://github.com/chanks/que] # * {queue_classic}[https://github.com/QueueClassic/queue_classic] - # * {Resque 1.x}[https://github.com/resque/resque/tree/1-x-stable] + # * {Resque}[https://github.com/resque/resque] # * {Sidekiq}[http://sidekiq.org] # * {Sneakers}[https://github.com/jondot/sneakers] # * {Sucker Punch}[https://github.com/brandonhilkert/sucker_punch] @@ -121,7 +123,7 @@ module ActiveJob autoload :SuckerPunchAdapter autoload :TestAdapter - ADAPTER = 'Adapter'.freeze + ADAPTER = "Adapter".freeze private_constant :ADAPTER class << self diff --git a/activejob/lib/active_job/queue_adapters/async_adapter.rb b/activejob/lib/active_job/queue_adapters/async_adapter.rb index 922bc4afce..ebf6f384e3 100644 --- a/activejob/lib/active_job/queue_adapters/async_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/async_adapter.rb @@ -1,7 +1,9 @@ -require 'securerandom' -require 'concurrent/scheduled_task' -require 'concurrent/executor/thread_pool_executor' -require 'concurrent/utility/processor_counter' +# frozen_string_literal: true + +require "securerandom" +require "concurrent/scheduled_task" +require "concurrent/executor/thread_pool_executor" +require "concurrent/utility/processor_counter" module ActiveJob module QueueAdapters @@ -29,7 +31,7 @@ module ActiveJob # jobs. Since jobs share a single thread pool, long-running jobs will block # short-lived jobs. Fine for dev/test; bad for production. class AsyncAdapter - # See {Concurrent::ThreadPoolExecutor}[http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/ThreadPoolExecutor.html] for executor options. + # See {Concurrent::ThreadPoolExecutor}[https://ruby-concurrency.github.io/concurrent-ruby/Concurrent/ThreadPoolExecutor.html] for executor options. def initialize(**executor_options) @scheduler = Scheduler.new(**executor_options) end diff --git a/activejob/lib/active_job/queue_adapters/backburner_adapter.rb b/activejob/lib/active_job/queue_adapters/backburner_adapter.rb index 17703e3e41..0ba93c6e0b 100644 --- a/activejob/lib/active_job/queue_adapters/backburner_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/backburner_adapter.rb @@ -1,4 +1,6 @@ -require 'backburner' +# frozen_string_literal: true + +require "backburner" module ActiveJob module QueueAdapters diff --git a/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb b/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb index 0a785fad3b..8eeef32b99 100644 --- a/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb @@ -1,4 +1,6 @@ -require 'delayed_job' +# frozen_string_literal: true + +require "delayed_job" module ActiveJob module QueueAdapters @@ -32,6 +34,10 @@ module ActiveJob @job_data = job_data end + def display_name + "#{job_data['job_class']} [#{job_data['job_id']}] from DelayedJob(#{job_data['queue_name']}) with arguments: #{job_data['arguments']}" + end + def perform Base.execute(job_data) end diff --git a/activejob/lib/active_job/queue_adapters/inline_adapter.rb b/activejob/lib/active_job/queue_adapters/inline_adapter.rb index 0496f8449e..3d0b590212 100644 --- a/activejob/lib/active_job/queue_adapters/inline_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/inline_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob module QueueAdapters # == Active Job Inline adapter diff --git a/activejob/lib/active_job/queue_adapters/qu_adapter.rb b/activejob/lib/active_job/queue_adapters/qu_adapter.rb index 0e198922fc..bd7003e177 100644 --- a/activejob/lib/active_job/queue_adapters/qu_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/qu_adapter.rb @@ -1,4 +1,6 @@ -require 'qu' +# frozen_string_literal: true + +require "qu" module ActiveJob module QueueAdapters @@ -20,7 +22,7 @@ module ActiveJob qu_job = Qu::Payload.new(klass: JobWrapper, args: [job.serialize]).tap do |payload| payload.instance_variable_set(:@queue, job.queue_name) end.push - + # qu_job can be nil depending on the configured backend job.provider_job_id = qu_job.id unless qu_job.nil? qu_job @@ -32,7 +34,7 @@ module ActiveJob class JobWrapper < Qu::Job #:nodoc: def initialize(job_data) - @job_data = job_data + @job_data = job_data end def perform diff --git a/activejob/lib/active_job/queue_adapters/que_adapter.rb b/activejob/lib/active_job/queue_adapters/que_adapter.rb index ab13689747..86b5e07743 100644 --- a/activejob/lib/active_job/queue_adapters/que_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/que_adapter.rb @@ -1,4 +1,6 @@ -require 'que' +# frozen_string_literal: true + +require "que" module ActiveJob module QueueAdapters diff --git a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb index 0ee41407d8..ccc1881091 100644 --- a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb @@ -1,4 +1,6 @@ -require 'queue_classic' +# frozen_string_literal: true + +require "queue_classic" module ActiveJob module QueueAdapters @@ -26,9 +28,9 @@ module ActiveJob def enqueue_at(job, timestamp) #:nodoc: queue = build_queue(job.queue_name) unless queue.respond_to?(:enqueue_at) - raise NotImplementedError, 'To be able to schedule jobs with queue_classic ' \ - 'the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. ' \ - 'You can implement this yourself or you can use the queue_classic-later gem.' + raise NotImplementedError, "To be able to schedule jobs with queue_classic " \ + "the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. " \ + "You can implement this yourself or you can use the queue_classic-later gem." end qc_job = queue.enqueue_at(timestamp, "#{JobWrapper.name}.perform", job.serialize) job.provider_job_id = qc_job["id"] if qc_job.is_a?(Hash) diff --git a/activejob/lib/active_job/queue_adapters/resque_adapter.rb b/activejob/lib/active_job/queue_adapters/resque_adapter.rb index 417854afd8..590b4ee98d 100644 --- a/activejob/lib/active_job/queue_adapters/resque_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/resque_adapter.rb @@ -1,12 +1,14 @@ -require 'resque' -require 'active_support/core_ext/enumerable' -require 'active_support/core_ext/array/access' +# frozen_string_literal: true + +require "resque" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/array/access" begin - require 'resque-scheduler' + require "resque-scheduler" rescue LoadError begin - require 'resque_scheduler' + require "resque_scheduler" rescue LoadError false end @@ -27,6 +29,7 @@ module ActiveJob # Rails.application.config.active_job.queue_adapter = :resque class ResqueAdapter def enqueue(job) #:nodoc: + JobWrapper.instance_variable_set(:@queue, job.queue_name) Resque.enqueue_to job.queue_name, JobWrapper, job.serialize end diff --git a/activejob/lib/active_job/queue_adapters/sidekiq_adapter.rb b/activejob/lib/active_job/queue_adapters/sidekiq_adapter.rb index c321776bf5..f726e6ad93 100644 --- a/activejob/lib/active_job/queue_adapters/sidekiq_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/sidekiq_adapter.rb @@ -1,4 +1,6 @@ -require 'sidekiq' +# frozen_string_literal: true + +require "sidekiq" module ActiveJob module QueueAdapters @@ -16,28 +18,28 @@ module ActiveJob # Rails.application.config.active_job.queue_adapter = :sidekiq class SidekiqAdapter def enqueue(job) #:nodoc: - #Sidekiq::Client does not support symbols as keys + # Sidekiq::Client does not support symbols as keys job.provider_job_id = Sidekiq::Client.push \ - 'class' => JobWrapper, - 'wrapped' => job.class.to_s, - 'queue' => job.queue_name, - 'args' => [ job.serialize ] + "class" => JobWrapper, + "wrapped" => job.class.to_s, + "queue" => job.queue_name, + "args" => [ job.serialize ] end def enqueue_at(job, timestamp) #:nodoc: job.provider_job_id = Sidekiq::Client.push \ - 'class' => JobWrapper, - 'wrapped' => job.class.to_s, - 'queue' => job.queue_name, - 'args' => [ job.serialize ], - 'at' => timestamp + "class" => JobWrapper, + "wrapped" => job.class.to_s, + "queue" => job.queue_name, + "args" => [ job.serialize ], + "at" => timestamp end class JobWrapper #:nodoc: include Sidekiq::Worker def perform(job_data) - Base.execute job_data + Base.execute job_data.merge("provider_job_id" => jid) end end end diff --git a/activejob/lib/active_job/queue_adapters/sneakers_adapter.rb b/activejob/lib/active_job/queue_adapters/sneakers_adapter.rb index d78bdecdcb..de98a950d0 100644 --- a/activejob/lib/active_job/queue_adapters/sneakers_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/sneakers_adapter.rb @@ -1,5 +1,7 @@ -require 'sneakers' -require 'monitor' +# frozen_string_literal: true + +require "sneakers" +require "monitor" module ActiveJob module QueueAdapters @@ -33,7 +35,7 @@ module ActiveJob class JobWrapper #:nodoc: include Sneakers::Worker - from_queue 'default' + from_queue "default" def work(msg) job_data = ActiveSupport::JSON.decode(msg) diff --git a/activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb b/activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb index 163c8eb212..d09e1e9143 100644 --- a/activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb @@ -1,4 +1,6 @@ -require 'sucker_punch' +# frozen_string_literal: true + +require "sucker_punch" module ActiveJob module QueueAdapters @@ -31,7 +33,7 @@ module ActiveJob delay = timestamp - Time.current.to_f JobWrapper.perform_in delay, job.serialize else - raise NotImplementedError, 'sucker_punch 1.0 does not support `enqueued_at`. Please upgrade to version ~> 2.0.0 to enable this behavior.' + raise NotImplementedError, "sucker_punch 1.0 does not support `enqueued_at`. Please upgrade to version ~> 2.0.0 to enable this behavior." end end diff --git a/activejob/lib/active_job/queue_adapters/test_adapter.rb b/activejob/lib/active_job/queue_adapters/test_adapter.rb index 9b7b7139f4..885f9ff01c 100644 --- a/activejob/lib/active_job/queue_adapters/test_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/test_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob module QueueAdapters # == Test adapter for Active Job @@ -10,7 +12,7 @@ module ActiveJob # # Rails.application.config.active_job.queue_adapter = :test class TestAdapter - attr_accessor(:perform_enqueued_jobs, :perform_enqueued_at_jobs, :filter) + attr_accessor(:perform_enqueued_jobs, :perform_enqueued_at_jobs, :filter, :reject) attr_writer(:enqueued_jobs, :performed_jobs) # Provides a store of all the enqueued jobs with the TestAdapter so you can check them. @@ -38,23 +40,28 @@ module ActiveJob end private + def job_to_hash(job, extras = {}) + { job: job.class, args: job.serialize.fetch("arguments"), queue: job.queue_name }.merge!(extras) + end - def job_to_hash(job, extras = {}) - { job: job.class, args: job.serialize.fetch('arguments'), queue: job.queue_name }.merge!(extras) - end - - def enqueue_or_perform(perform, job, job_data) - if perform - performed_jobs << job_data - Base.execute job.serialize - else - enqueued_jobs << job_data + def enqueue_or_perform(perform, job, job_data) + if perform + performed_jobs << job_data + Base.execute job.serialize + else + enqueued_jobs << job_data + end end - end - def filtered?(job) - filter && !Array(filter).include?(job.class) - end + def filtered?(job) + if filter + !Array(filter).include?(job.class) + elsif reject + Array(reject).include?(job.class) + else + false + end + end end end end diff --git a/activejob/lib/active_job/queue_name.rb b/activejob/lib/active_job/queue_name.rb index 65786a49ff..9dc6bc7f2e 100644 --- a/activejob/lib/active_job/queue_name.rb +++ b/activejob/lib/active_job/queue_name.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + module ActiveJob module QueueName extend ActiveSupport::Concern # Includes the ability to override the default queue name and prefix. module ClassMethods - mattr_accessor(:queue_name_prefix) - mattr_accessor(:default_queue_name) { "default" } + mattr_accessor :queue_name_prefix + mattr_accessor :default_queue_name, default: "default" # Specifies the name of the queue to process the job on. # @@ -16,7 +18,7 @@ module ActiveJob # post.to_feed! # end # end - def queue_as(part_name=nil, &block) + def queue_as(part_name = nil, &block) if block_given? self.queue_name = block else @@ -32,11 +34,8 @@ module ActiveJob end included do - class_attribute :queue_name, instance_accessor: false - class_attribute :queue_name_delimiter, instance_accessor: false - - self.queue_name = default_queue_name - self.queue_name_delimiter = '_' # set default delimiter to '_' + class_attribute :queue_name, instance_accessor: false, default: default_queue_name + class_attribute :queue_name_delimiter, instance_accessor: false, default: "_" end # Returns the name of the queue the job will be run on. @@ -46,6 +45,5 @@ module ActiveJob end @queue_name end - end end diff --git a/activejob/lib/active_job/queue_priority.rb b/activejob/lib/active_job/queue_priority.rb index 01d84910ff..063bccdb01 100644 --- a/activejob/lib/active_job/queue_priority.rb +++ b/activejob/lib/active_job/queue_priority.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + module ActiveJob module QueuePriority extend ActiveSupport::Concern # Includes the ability to override the default queue priority. module ClassMethods - mattr_accessor(:default_priority) + mattr_accessor :default_priority # Specifies the priority of the queue to create the job with. # @@ -17,7 +19,7 @@ module ActiveJob # end # # Specify either an argument or a block. - def queue_with_priority(priority=nil, &block) + def queue_with_priority(priority = nil, &block) if block_given? self.priority = block else @@ -27,9 +29,7 @@ module ActiveJob end included do - class_attribute :priority, instance_accessor: false - - self.priority = default_priority + class_attribute :priority, instance_accessor: false, default: default_priority end # Returns the priority that the job will be created with @@ -39,6 +39,5 @@ module ActiveJob end @priority end - end end diff --git a/activejob/lib/active_job/railtie.rb b/activejob/lib/active_job/railtie.rb index a47caa4a7e..7b0742a6d2 100644 --- a/activejob/lib/active_job/railtie.rb +++ b/activejob/lib/active_job/railtie.rb @@ -1,12 +1,14 @@ -require 'global_id/railtie' -require 'active_job' +# frozen_string_literal: true + +require "global_id/railtie" +require "active_job" module ActiveJob # = Active Job Railtie class Railtie < Rails::Railtie # :nodoc: config.active_job = ActiveSupport::OrderedOptions.new - initializer 'active_job.logger' do + initializer "active_job.logger" do ActiveSupport.on_load(:active_job) { self.logger = ::Rails.logger } end @@ -15,7 +17,7 @@ module ActiveJob options.queue_adapter ||= :async ActiveSupport.on_load(:active_job) do - options.each { |k,v| send("#{k}=", v) } + options.each { |k, v| send("#{k}=", v) } end end diff --git a/activejob/lib/active_job/test_case.rb b/activejob/lib/active_job/test_case.rb index d894a7b5cd..49cd51bdd0 100644 --- a/activejob/lib/active_job/test_case.rb +++ b/activejob/lib/active_job/test_case.rb @@ -1,7 +1,11 @@ -require 'active_support/test_case' +# frozen_string_literal: true + +require "active_support/test_case" module ActiveJob class TestCase < ActiveSupport::TestCase include ActiveJob::TestHelper + + ActiveSupport.run_load_hooks(:active_job_test_case, self) end end diff --git a/activejob/lib/active_job/test_helper.rb b/activejob/lib/active_job/test_helper.rb index e16af1947f..1cd2c40c15 100644 --- a/activejob/lib/active_job/test_helper.rb +++ b/activejob/lib/active_job/test_helper.rb @@ -1,5 +1,7 @@ -require 'active_support/core_ext/class/subclasses' -require 'active_support/core_ext/hash/keys' +# frozen_string_literal: true + +require "active_support/core_ext/class/subclasses" +require "active_support/core_ext/hash/keys" module ActiveJob # Provides helper methods for testing Active Job @@ -8,16 +10,35 @@ module ActiveJob :performed_jobs, :performed_jobs=, to: :queue_adapter + module TestQueueAdapter + extend ActiveSupport::Concern + + included do + class_attribute :_test_adapter, instance_accessor: false, instance_predicate: false + end + + module ClassMethods + def queue_adapter + self._test_adapter.nil? ? super : self._test_adapter + end + + def disable_test_adapter + self._test_adapter = nil + end + + def enable_test_adapter(test_adapter) + self._test_adapter = test_adapter + end + end + end + + ActiveJob::Base.include(TestQueueAdapter) + def before_setup # :nodoc: test_adapter = queue_adapter_for_test - @old_queue_adapters = (ActiveJob::Base.subclasses << ActiveJob::Base).select do |klass| - # only override explicitly set adapters, a quirk of `class_attribute` - klass.singleton_class.public_instance_methods(false).include?(:_queue_adapter) - end.map do |klass| - [klass, klass.queue_adapter].tap do - klass.queue_adapter = test_adapter - end + queue_adapter_changed_jobs.each do |klass| + klass.enable_test_adapter(test_adapter) end clear_enqueued_jobs @@ -27,9 +48,8 @@ module ActiveJob def after_teardown # :nodoc: super - @old_queue_adapters.each do |(klass, adapter)| - klass.queue_adapter = adapter - end + + queue_adapter_changed_jobs.each { |klass| klass.disable_test_adapter } end # Specifies the queue adapter to use with all active job test helpers. @@ -55,7 +75,7 @@ module ActiveJob # assert_enqueued_jobs 2 # end # - # If a block is passed, that block should cause the specified number of + # If a block is passed, that block will cause the specified number of # jobs to be enqueued. # # def test_jobs_again @@ -69,7 +89,7 @@ module ActiveJob # end # end # - # The number of times a specific job is enqueued can be asserted. + # The number of times a specific job was enqueued can be asserted. # # def test_logging_job # assert_enqueued_jobs 1, only: LoggingJob do @@ -77,14 +97,32 @@ module ActiveJob # HelloJob.perform_later('jeremy') # end # end - def assert_enqueued_jobs(number, only: nil) + # + # The number of times a job except specific class was enqueued can be asserted. + # + # def test_logging_job + # assert_enqueued_jobs 1, except: HelloJob do + # LoggingJob.perform_later + # HelloJob.perform_later('jeremy') + # end + # end + # + # The number of times a job is enqueued to a specific queue can also be asserted. + # + # def test_logging_job + # assert_enqueued_jobs 2, queue: 'default' do + # LoggingJob.perform_later + # HelloJob.perform_later('elfassy') + # end + # end + def assert_enqueued_jobs(number, only: nil, except: nil, queue: nil) if block_given? - original_count = enqueued_jobs_size(only: only) + original_count = enqueued_jobs_size(only: only, except: except, queue: queue) yield - new_count = enqueued_jobs_size(only: only) + new_count = enqueued_jobs_size(only: only, except: except, queue: queue) assert_equal number, new_count - original_count, "#{number} jobs expected, but #{new_count - original_count} were enqueued" else - actual_count = enqueued_jobs_size(only: only) + actual_count = enqueued_jobs_size(only: only, except: except, queue: queue) assert_equal number, actual_count, "#{number} jobs expected, but #{actual_count} were enqueued" end end @@ -113,11 +151,19 @@ module ActiveJob # end # end # + # It can be asserted that no jobs except specific class are enqueued: + # + # def test_no_logging + # assert_no_enqueued_jobs except: HelloJob do + # HelloJob.perform_later('jeremy') + # end + # end + # # Note: This assertion is simply a shortcut for: # # assert_enqueued_jobs 0, &block - def assert_no_enqueued_jobs(only: nil, &block) - assert_enqueued_jobs 0, only: only, &block + def assert_no_enqueued_jobs(only: nil, except: nil, &block) + assert_enqueued_jobs 0, only: only, except: except, &block end # Asserts that the number of performed jobs matches the given number. @@ -162,6 +208,16 @@ module ActiveJob # end # end # + # Also if the :except option is specified, + # then the job(s) except specific class will be performed. + # + # def test_hello_job + # assert_performed_jobs 1, except: LoggingJob do + # HelloJob.perform_later('jeremy') + # LoggingJob.perform_later + # end + # end + # # An array may also be specified, to support testing multiple jobs. # # def test_hello_and_logging_jobs @@ -173,10 +229,10 @@ module ActiveJob # end # end # end - def assert_performed_jobs(number, only: nil) + def assert_performed_jobs(number, only: nil, except: nil) if block_given? original_count = performed_jobs.size - perform_enqueued_jobs(only: only) { yield } + perform_enqueued_jobs(only: only, except: except) { yield } new_count = performed_jobs.size assert_equal number, new_count - original_count, "#{number} jobs expected, but #{new_count - original_count} were performed" @@ -214,11 +270,20 @@ module ActiveJob # end # end # + # Also if the :except option is specified, + # then the job(s) except specific class will not be performed. + # + # def test_no_logging + # assert_no_performed_jobs except: HelloJob do + # HelloJob.perform_later('jeremy') + # end + # end + # # Note: This assertion is simply a shortcut for: # # assert_performed_jobs 0, &block - def assert_no_performed_jobs(only: nil, &block) - assert_performed_jobs 0, only: only, &block + def assert_no_performed_jobs(only: nil, except: nil, &block) + assert_performed_jobs 0, only: only, except: except, &block end # Asserts that the job passed in the block has been enqueued with the given arguments. @@ -232,16 +297,16 @@ module ActiveJob # MyJob.set(wait_until: Date.tomorrow.noon).perform_later # end # end - def assert_enqueued_with(args = {}) + def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil) original_enqueued_jobs_count = enqueued_jobs.count - args.assert_valid_keys(:job, :args, :at, :queue) - serialized_args = serialize_args_for_assertion(args) + expected = { job: job, args: args, at: at, queue: queue }.compact + serialized_args = serialize_args_for_assertion(expected) yield in_block_jobs = enqueued_jobs.drop(original_enqueued_jobs_count) - matching_job = in_block_jobs.find do |job| - serialized_args.all? { |key, value| value == job[key] } + matching_job = in_block_jobs.find do |in_block_job| + serialized_args.all? { |key, value| value == in_block_job[key] } end - assert matching_job, "No enqueued job found with #{args}" + assert matching_job, "No enqueued job found with #{expected}" instantiate_job(matching_job) end @@ -256,69 +321,128 @@ module ActiveJob # MyJob.set(wait_until: Date.tomorrow.noon).perform_later # end # end - def assert_performed_with(args = {}) + def assert_performed_with(job: nil, args: nil, at: nil, queue: nil) original_performed_jobs_count = performed_jobs.count - args.assert_valid_keys(:job, :args, :at, :queue) - serialized_args = serialize_args_for_assertion(args) + expected = { job: job, args: args, at: at, queue: queue }.compact + serialized_args = serialize_args_for_assertion(expected) perform_enqueued_jobs { yield } in_block_jobs = performed_jobs.drop(original_performed_jobs_count) - matching_job = in_block_jobs.find do |job| - serialized_args.all? { |key, value| value == job[key] } + matching_job = in_block_jobs.find do |in_block_job| + serialized_args.all? { |key, value| value == in_block_job[key] } end - assert matching_job, "No performed job found with #{args}" + assert matching_job, "No performed job found with #{expected}" instantiate_job(matching_job) end - def perform_enqueued_jobs(only: nil) + # Performs all enqueued jobs in the duration of the block. + # + # def test_perform_enqueued_jobs + # perform_enqueued_jobs do + # MyJob.perform_later(1, 2, 3) + # end + # assert_performed_jobs 1 + # end + # + # This method also supports filtering. If the +:only+ option is specified, + # then only the listed job(s) will be performed. + # + # def test_perform_enqueued_jobs_with_only + # perform_enqueued_jobs(only: MyJob) do + # MyJob.perform_later(1, 2, 3) # will be performed + # HelloJob.perform_later(1, 2, 3) # will not be performed + # end + # assert_performed_jobs 1 + # end + # + # Also if the +:except+ option is specified, + # then the job(s) except specific class will be performed. + # + # def test_perform_enqueued_jobs_with_except + # perform_enqueued_jobs(except: HelloJob) do + # MyJob.perform_later(1, 2, 3) # will be performed + # HelloJob.perform_later(1, 2, 3) # will not be performed + # end + # assert_performed_jobs 1 + # end + # + def perform_enqueued_jobs(only: nil, except: nil) + validate_option(only: only, except: except) old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs old_filter = queue_adapter.filter + old_reject = queue_adapter.reject begin queue_adapter.perform_enqueued_jobs = true queue_adapter.perform_enqueued_at_jobs = true queue_adapter.filter = only + queue_adapter.reject = except yield ensure queue_adapter.perform_enqueued_jobs = old_perform_enqueued_jobs queue_adapter.perform_enqueued_at_jobs = old_perform_enqueued_at_jobs queue_adapter.filter = old_filter + queue_adapter.reject = old_reject end end + # Accesses the queue_adapter set by ActiveJob::Base. + # + # def test_assert_job_has_custom_queue_adapter_set + # assert_instance_of CustomQueueAdapter, HelloJob.queue_adapter + # end def queue_adapter ActiveJob::Base.queue_adapter end private - def clear_enqueued_jobs # :nodoc: + def clear_enqueued_jobs enqueued_jobs.clear end - def clear_performed_jobs # :nodoc: + def clear_performed_jobs performed_jobs.clear end - def enqueued_jobs_size(only: nil) # :nodoc: - if only - enqueued_jobs.count { |job| Array(only).include?(job.fetch(:job)) } - else - enqueued_jobs.count + def enqueued_jobs_size(only: nil, except: nil, queue: nil) + validate_option(only: only, except: except) + enqueued_jobs.count do |job| + job_class = job.fetch(:job) + if only + next false unless Array(only).include?(job_class) + elsif except + next false if Array(except).include?(job_class) + end + if queue + next false unless queue.to_s == job.fetch(:queue, job_class.queue_name) + end + true end end - def serialize_args_for_assertion(args) # :nodoc: + def serialize_args_for_assertion(args) args.dup.tap do |serialized_args| serialized_args[:args] = ActiveJob::Arguments.serialize(serialized_args[:args]) if serialized_args[:args] serialized_args[:at] = serialized_args[:at].to_f if serialized_args[:at] end end - def instantiate_job(payload) # :nodoc: + def instantiate_job(payload) job = payload[:job].new(*payload[:args]) job.scheduled_at = Time.at(payload[:at]) if payload.key?(:at) job.queue_name = payload[:queue] job end + + def queue_adapter_changed_jobs + (ActiveJob::Base.descendants << ActiveJob::Base).select do |klass| + # only override explicitly set adapters, a quirk of `class_attribute` + klass.singleton_class.public_instance_methods(false).include?(:_queue_adapter) + end + end + + def validate_option(only: nil, except: nil) + raise ArgumentError, "Cannot specify both `:only` and `:except` options." if only && except + end end end diff --git a/activejob/lib/active_job/translation.rb b/activejob/lib/active_job/translation.rb index 67e4cf4ab9..fb45c80d67 100644 --- a/activejob/lib/active_job/translation.rb +++ b/activejob/lib/active_job/translation.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveJob module Translation #:nodoc: extend ActiveSupport::Concern diff --git a/activejob/lib/active_job/version.rb b/activejob/lib/active_job/version.rb index 971ba9fe0c..eae7da4d05 100644 --- a/activejob/lib/active_job/version.rb +++ b/activejob/lib/active_job/version.rb @@ -1,4 +1,6 @@ -require_relative 'gem_version' +# frozen_string_literal: true + +require_relative "gem_version" module ActiveJob # Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt> |