File: sidekiq_api_usage.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (39 lines) | stat: -rw-r--r-- 1,367 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

module RuboCop
  module Cop
    class SidekiqApiUsage < RuboCop::Cop::Base
      MSG = 'Refrain from directly using Sidekiq APIs. ' \
          'Only permitted in migrations, administrations and Sidekiq middlewares. ' \
          'When disabling the cop, ensure that Sidekiq APIs are wrapped with ' \
          'Sidekiq::Client.via(..) { ... } block to remain shard aware. ' \
          'See doc/development/sidekiq/index.md#sharding for more information.'

      ALLOWED_WORKER_METHODS = [
        :skipping_transaction_check,
        :raise_inside_transaction_exception,
        :raise_exception_for_being_inside_a_transaction?
      ].freeze

      ALLOWED_CLIENT_METHODS = [:via].freeze

      def_node_matcher :using_sidekiq_api?, <<~PATTERN
        (send (const (const nil? :Sidekiq) $_  ) $... )
      PATTERN

      def on_send(node)
        using_sidekiq_api?(node) do |klass, methods_called|
          next if klass == :Testing

          # allow methods defined in config/initializers/forbid_sidekiq_in_transactions.rb
          next if klass == :Worker && ALLOWED_WORKER_METHODS.include?(methods_called[0])

          # allow Sidekiq::Client.via calls
          next if klass == :Client && ALLOWED_CLIENT_METHODS.include?(methods_called[0])

          add_offense(node, message: MSG)
        end
      end
    end
  end
end