1# frozen_string_literal: true
2
3module RuboCop
4  module Cop
5    module Scalability
6      class CronWorkerContext < RuboCop::Cop::Cop
7        MSG = <<~MSG
8          Manually define an ApplicationContext for cronjob-workers. The context
9          is required to add metadata to our logs.
10
11          If there is no relevant metadata, please disable the cop with a comment
12          explaining this.
13
14          Read more about it https://docs.gitlab.com/ee/development/sidekiq_style_guide.html#worker-context
15        MSG
16
17        def_node_matcher :includes_cronjob_queue?, <<~PATTERN
18          (send nil? :include (const nil? :CronjobQueue))
19        PATTERN
20
21        def_node_search :defines_contexts?, <<~PATTERN
22         (send nil? :with_context _)
23        PATTERN
24
25        def_node_search :schedules_with_batch_context?, <<~PATTERN
26          (send (...) {:bulk_perform_async_with_contexts :bulk_perform_in_with_contexts} _*)
27        PATTERN
28
29        def on_send(node)
30          return unless includes_cronjob_queue?(node)
31          return if defines_contexts?(node.parent)
32          return if schedules_with_batch_context?(node.parent)
33
34          add_offense(node.arguments.first, location: :expression)
35        end
36      end
37    end
38  end
39end
40