Class: RuboCop::Cop::Sidekiq::TransactionLeak

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/sidekiq/transaction_leak.rb

Overview

Checks for Sidekiq jobs enqueued inside database transactions.

Enqueuing jobs inside a transaction can lead to race conditions where the job runs before the transaction commits, causing the job to see stale data or fail to find the record.

Examples:

# bad
ActiveRecord::Base.transaction do
  user.save!
  NotificationJob.perform_async(user.id)
end

# good - enqueue after transaction
user.save!
NotificationJob.perform_async(user.id)

# good - use after_commit callback
class User < ApplicationRecord
  after_commit :send_notification, on: :create

  def send_notification
    NotificationJob.perform_async(id)
  end
end

Constant Summary collapse

MSG =
'Do not enqueue Sidekiq jobs inside database transactions. ' \
'The job may run before the transaction commits.'
RESTRICT_ON_SEND =
PerformMethods.all

Instance Method Summary collapse

Methods included from Sidekiq::Language

#active_job_class?, #sidekiq_include?, #sidekiq_options_call?

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



43
44
45
46
47
48
# File 'lib/rubocop/cop/sidekiq/transaction_leak.rb', line 43

def on_send(node)
  return unless perform_call?(node)
  return unless inside_transaction?(node)

  add_offense(node)
end

#perform_call?(node) ⇒ Object



39
40
41
# File 'lib/rubocop/cop/sidekiq/transaction_leak.rb', line 39

def_node_matcher :perform_call?, <<~PATTERN
  (send _ {#{RESTRICT_ON_SEND.map(&:inspect).join(' ')}} ...)
PATTERN