1
0
Fork 0
mirror of https://github.com/mperham/sidekiq.git synced 2022-11-09 13:52:34 -05:00
mperham--sidekiq/lib/sidekiq.rb

273 lines
7.1 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
require "sidekiq/version"
fail "Sidekiq #{Sidekiq::VERSION} does not support Ruby versions below 2.5.0." if RUBY_PLATFORM != "java" && Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.5.0")
2014-07-10 09:49:21 -04:00
require "sidekiq/logger"
require "sidekiq/client"
require "sidekiq/worker"
2021-09-08 18:42:22 -04:00
require "sidekiq/job"
require "sidekiq/redis_connection"
require "sidekiq/delay"
2012-02-17 16:39:36 -05:00
require "json"
2012-02-17 16:39:36 -05:00
module Sidekiq
NAME = "Sidekiq"
LICENSE = "See LICENSE and the LGPL-3.0 for licensing details."
DEFAULTS = {
queues: [],
labels: [],
concurrency: 10,
require: ".",
strict: true,
environment: nil,
timeout: 25,
poll_interval_average: nil,
average_scheduled_poll_interval: 5,
on_complex_arguments: :warn,
error_handlers: [],
death_handlers: [],
lifecycle_events: {
startup: [],
quiet: [],
shutdown: [],
2020-03-17 16:38:48 -04:00
heartbeat: []
},
dead_max_jobs: 10_000,
2016-02-01 18:59:20 -05:00
dead_timeout_in_seconds: 180 * 24 * 60 * 60, # 6 months
2020-03-17 16:38:48 -04:00
reloader: proc { |&block| block.call }
}
FAKE_INFO = {
"redis_version" => "9.9.9",
"uptime_in_days" => "9999",
"connected_clients" => "9999",
"used_memory_human" => "9P",
2020-03-17 16:38:48 -04:00
"used_memory_peak_human" => "9P"
}
def self.°°
puts "Calm down, yo."
2013-02-08 15:42:06 -05:00
end
def self.options
@options ||= DEFAULTS.dup
end
def self.options=(opts)
@options = opts
end
##
# Configuration for Sidekiq server, use like:
#
# Sidekiq.configure_server do |config|
# config.redis = { :namespace => 'myapp', :size => 25, :url => 'redis://myhost:8877/0' }
# config.server_middleware do |chain|
# chain.add MyServerHook
# end
# end
def self.configure_server
yield self if server?
end
##
# Configuration for Sidekiq client, use like:
#
# Sidekiq.configure_client do |config|
# config.redis = { :namespace => 'myapp', :size => 1, :url => 'redis://myhost:8877/0' }
# end
def self.configure_client
yield self unless server?
end
def self.server?
defined?(Sidekiq::CLI)
end
def self.redis
raise ArgumentError, "requires a block" unless block_given?
redis_pool.with do |conn|
retryable = true
begin
yield conn
rescue Redis::BaseError => ex
# 2550 Failover can cause the server to become a replica, need
2018-12-28 13:07:03 -05:00
# to disconnect and reopen the socket to get back to the primary.
# 4495 Use the same logic if we have a "Not enough replicas" error from the primary
# 4985 Use the same logic when a blocking command is force-unblocked
# The same retry logic is also used in client.rb
if retryable && ex.message =~ /READONLY|NOREPLICAS|UNBLOCKED/
conn.disconnect!
retryable = false
retry
end
raise
end
end
end
def self.redis_info
redis do |conn|
# admin commands can't go through redis-namespace starting
# in redis-namespace 2.0
if conn.respond_to?(:namespace)
conn.redis.info
else
conn.info
end
rescue Redis::CommandError => ex
# 2850 return fake version when INFO command has (probably) been renamed
raise unless /unknown command/.match?(ex.message)
FAKE_INFO
end
end
def self.redis_pool
@redis ||= Sidekiq::RedisConnection.create
end
def self.redis=(hash)
@redis = if hash.is_a?(ConnectionPool)
hash
else
Sidekiq::RedisConnection.create(hash)
end
2012-02-17 16:39:36 -05:00
end
2013-10-24 00:58:15 -04:00
def self.client_middleware
@client_chain ||= Middleware::Chain.new
yield @client_chain if block_given?
@client_chain
end
def self.server_middleware
@server_chain ||= default_server_middleware
yield @server_chain if block_given?
@server_chain
end
def self.default_server_middleware
Middleware::Chain.new
end
def self.default_worker_options=(hash) # deprecated
@default_job_options = default_job_options.merge(hash.transform_keys(&:to_s))
end
def self.default_job_options=(hash)
@default_job_options = default_job_options.merge(hash.transform_keys(&:to_s))
end
def self.default_worker_options # deprecated
@default_job_options ||= {"retry" => true, "queue" => "default"}
2013-09-07 12:54:13 -04:00
end
def self.default_job_options
@default_job_options ||= {"retry" => true, "queue" => "default"}
2013-09-07 12:54:13 -04:00
end
##
# Death handlers are called when all retries for a job have been exhausted and
# the job dies. It's the notification to your application
# that this job will not succeed without manual intervention.
#
# Sidekiq.configure_server do |config|
# config.death_handlers << ->(job, ex) do
# end
# end
def self.death_handlers
options[:death_handlers]
end
2012-04-22 22:22:09 -04:00
def self.load_json(string)
2013-05-12 17:33:49 -04:00
JSON.parse(string)
end
2012-04-22 22:22:09 -04:00
def self.dump_json(object)
2013-05-12 17:33:49 -04:00
JSON.generate(object)
end
def self.log_formatter
@log_formatter ||= if ENV["DYNO"]
Sidekiq::Logger::Formatters::WithoutTimestamp.new
else
Sidekiq::Logger::Formatters::Pretty.new
end
end
def self.log_formatter=(log_formatter)
@log_formatter = log_formatter
logger.formatter = log_formatter
end
def self.logger
2020-08-28 15:40:19 -04:00
@logger ||= Sidekiq::Logger.new($stdout, level: Logger::INFO)
end
def self.logger=(logger)
2019-09-03 14:05:48 -04:00
if logger.nil?
self.logger.level = Logger::FATAL
return self.logger
end
2019-09-25 18:52:48 -04:00
logger.extend(Sidekiq::LoggingUtils)
@logger = logger
2012-06-26 12:01:54 -04:00
end
def self.pro?
defined?(Sidekiq::Pro)
end
# How frequently Redis should be checked by a random Sidekiq process for
# scheduled and retriable jobs. Each individual process will take turns by
# waiting some multiple of this value.
#
# See sidekiq/scheduled.rb for an in-depth explanation of this value
def self.average_scheduled_poll_interval=(interval)
options[:average_scheduled_poll_interval] = interval
end
2014-03-23 18:44:37 -04:00
# Register a proc to handle any error which occurs within the Sidekiq process.
#
# Sidekiq.configure_server do |config|
# config.error_handlers << proc {|ex,ctx_hash| MyErrorService.notify(ex, ctx_hash) }
2014-03-23 18:44:37 -04:00
# end
#
# The default error handler logs errors to Sidekiq.logger.
2014-02-24 23:47:44 -05:00
def self.error_handlers
options[:error_handlers]
2014-02-24 23:47:44 -05:00
end
2014-03-23 18:44:37 -04:00
# Register a block to run at a point in the Sidekiq lifecycle.
# :startup, :quiet or :shutdown are valid events.
#
# Sidekiq.configure_server do |config|
# config.on(:shutdown) do
# puts "Goodbye cruel world!"
# end
# end
def self.on(event, &block)
2014-07-10 09:49:21 -04:00
raise ArgumentError, "Symbols only please: #{event}" unless event.is_a?(Symbol)
raise ArgumentError, "Invalid event name: #{event}" unless options[:lifecycle_events].key?(event)
options[:lifecycle_events][event] << block
end
2022-01-05 22:54:12 -05:00
def self.strict_args!(mode = :raise)
options[:on_complex_arguments] = mode
Implement strict argument checking (#5071) * Add the outline of failing tests * Implement argument checking * Move argument checking into Sidekiq::JobUtil#validate * Refactor acceptable class definition into a constant to cut down on array allocations * Improve error message, match raise call formatting to other errors in the class * Address feedback in the Pull Request to use the JSON round-trip method of confirming the safety of job argument payloads. Cleanup commented-out code from a few years back. Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Swap out JSON.load for JSON.parse per the security CI check Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Add a few more tests cases to build up confidence around our JSON.parse/dump approach and deep structures Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Improve test case description * Warn when job arguments do not serialize safely and point folks toward how to enable strict_mode and the best practice * Reconfigure the options-hash based approach to a global Sidekiq.strict_mode! method * Add a note in the raised error on how to disable the error * Let the error message breathe a little bit * Toggle strict_mode! off to suss out a test flake * Capitalize the start of a sentence * Rename job_is_json_safe to json_safe? Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Refactor a few tests to test a single argument at a time Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Break out test cases to exercise each individual intersting case instead of all at once Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Change formatting to be more consistent, tighter when arguments are simple Co-authored-by: Eda Zhou <eda.zhou@gusto.com> * Add a flag to disable the warning message for development warning messages Co-authored-by: Eda Zhou <eda.zhou@gusto.com> Co-authored-by: Eda Zhou <eda.zhou@gusto.com>
2021-12-07 16:20:20 -05:00
end
# We are shutting down Sidekiq but what about threads that
# are working on some long job? This error is
# raised in jobs that have not finished within the hard
# timeout limit. This is needed to rollback db transactions,
# otherwise Ruby's Thread#kill will commit. See #377.
# DO NOT RESCUE THIS ERROR IN YOUR JOBS
class Shutdown < Interrupt; end
2012-02-17 16:39:36 -05:00
end
require "sidekiq/rails" if defined?(::Rails::Engine)