2017-02-20 08:28:05 -05:00
|
|
|
module Sidekiq
|
|
|
|
module Worker
|
2017-12-22 05:38:35 -05:00
|
|
|
EnqueueFromTransactionError = Class.new(StandardError)
|
|
|
|
|
2017-06-02 13:12:08 -04:00
|
|
|
def self.skipping_transaction_check(&block)
|
2019-07-04 09:46:46 -04:00
|
|
|
previous_skip_transaction_check = self.skip_transaction_check
|
|
|
|
Thread.current[:sidekiq_worker_skip_transaction_check] = true
|
2017-06-02 13:12:08 -04:00
|
|
|
yield
|
|
|
|
ensure
|
2019-07-04 09:46:46 -04:00
|
|
|
Thread.current[:sidekiq_worker_skip_transaction_check] = previous_skip_transaction_check
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.skip_transaction_check
|
|
|
|
Thread.current[:sidekiq_worker_skip_transaction_check]
|
2017-06-02 13:12:08 -04:00
|
|
|
end
|
2017-06-01 17:35:32 -04:00
|
|
|
|
2017-02-20 08:28:05 -05:00
|
|
|
module ClassMethods
|
2017-12-22 05:38:35 -05:00
|
|
|
module NoEnqueueingFromTransactions
|
2017-02-20 08:28:05 -05:00
|
|
|
%i(perform_async perform_at perform_in).each do |name|
|
|
|
|
define_method(name) do |*args|
|
2019-06-25 05:15:35 -04:00
|
|
|
if !Sidekiq::Worker.skip_transaction_check && Gitlab::Database.inside_transaction?
|
2018-03-05 06:31:23 -05:00
|
|
|
begin
|
|
|
|
raise Sidekiq::Worker::EnqueueFromTransactionError, <<~MSG
|
2017-11-29 10:30:17 -05:00
|
|
|
`#{self}.#{name}` cannot be called inside a transaction as this can lead to
|
|
|
|
race conditions when the worker runs before the transaction is committed and
|
|
|
|
tries to access a model that has not been saved yet.
|
2017-02-20 08:28:05 -05:00
|
|
|
|
2017-11-29 10:30:17 -05:00
|
|
|
Use an `after_commit` hook, or include `AfterCommitQueue` and use a `run_after_commit` block instead.
|
2018-03-05 06:31:23 -05:00
|
|
|
MSG
|
|
|
|
rescue Sidekiq::Worker::EnqueueFromTransactionError => e
|
2018-05-04 01:56:46 -04:00
|
|
|
::Rails.logger.error(e.message) if ::Rails.env.production?
|
2018-04-13 12:32:54 -04:00
|
|
|
Gitlab::Sentry.track_exception(e)
|
2018-03-05 06:31:23 -05:00
|
|
|
end
|
2017-11-29 10:30:17 -05:00
|
|
|
end
|
2017-02-20 08:28:05 -05:00
|
|
|
|
2017-11-29 10:30:17 -05:00
|
|
|
super(*args)
|
2017-02-20 08:28:05 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-12-22 05:38:35 -05:00
|
|
|
prepend NoEnqueueingFromTransactions
|
2017-02-20 08:28:05 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2017-06-01 17:35:32 -04:00
|
|
|
|
|
|
|
module ActiveRecord
|
|
|
|
class Base
|
2017-06-02 13:12:08 -04:00
|
|
|
module SkipTransactionCheckAfterCommit
|
2017-06-01 17:35:32 -04:00
|
|
|
def committed!(*)
|
2017-06-02 13:12:08 -04:00
|
|
|
Sidekiq::Worker.skipping_transaction_check { super }
|
2017-06-01 17:35:32 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-06-02 13:12:08 -04:00
|
|
|
prepend SkipTransactionCheckAfterCommit
|
2017-06-01 17:35:32 -04:00
|
|
|
end
|
|
|
|
end
|