Welcome to mirror list, hosted at ThFree Co, Russian Federation.

worker_context.rb « concerns « workers « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6acb9acceeb0e13a44f1ac6acdddeaa4af8cca58 (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

module WorkerContext
  extend ActiveSupport::Concern

  class_methods do
    def worker_context(attributes)
      @worker_context = Gitlab::ApplicationContext.new(**attributes)
    end

    def get_worker_context
      @worker_context || superclass_context
    end

    def bulk_perform_async_with_contexts(objects, arguments_proc:, context_proc:)
      with_batch_contexts(objects, arguments_proc, context_proc) do |arguments|
        bulk_perform_async(arguments)
      end
    end

    def bulk_perform_in_with_contexts(delay, objects, arguments_proc:, context_proc:)
      with_batch_contexts(objects, arguments_proc, context_proc) do |arguments|
        bulk_perform_in(delay, arguments)
      end
    end

    def context_for_arguments(args)
      batch_context&.context_for(args)
    end

    private

    BATCH_CONTEXT_KEY = "#{name}_batch_context"

    def batch_context
      Thread.current[BATCH_CONTEXT_KEY]
    end

    def batch_context=(value)
      Thread.current[BATCH_CONTEXT_KEY] = value
    end

    def with_batch_contexts(objects, arguments_proc, context_proc)
      self.batch_context = Gitlab::BatchWorkerContext.new(
        objects,
        arguments_proc: arguments_proc,
        context_proc: context_proc
      )

      yield(batch_context.arguments)
    ensure
      self.batch_context = nil
    end

    def superclass_context
      return unless superclass.include?(WorkerContext)

      superclass.get_worker_context
    end
  end

  def with_context(context, &block)
    Gitlab::ApplicationContext.new(**context).use { yield(**context) }
  end
end