2020-01-24 07:09:01 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module WorkerContext
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
class_methods do
|
|
|
|
def worker_context(attributes)
|
2020-12-09 22:09:53 -05:00
|
|
|
@worker_context = Gitlab::ApplicationContext.new(**attributes)
|
2020-01-24 07:09:01 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def get_worker_context
|
|
|
|
@worker_context || superclass_context
|
|
|
|
end
|
|
|
|
|
2020-01-31 04:08:53 -05:00
|
|
|
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
|
|
|
|
|
2020-01-24 07:09:01 -05:00
|
|
|
private
|
|
|
|
|
2020-01-31 04:08:53 -05:00
|
|
|
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
|
|
|
|
|
2020-01-24 07:09:01 -05:00
|
|
|
def superclass_context
|
|
|
|
return unless superclass.include?(WorkerContext)
|
|
|
|
|
|
|
|
superclass.get_worker_context
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def with_context(context, &block)
|
2020-12-09 22:09:53 -05:00
|
|
|
Gitlab::ApplicationContext.new(**context).use { yield(**context) }
|
2020-01-24 07:09:01 -05:00
|
|
|
end
|
|
|
|
end
|