From f4aac773894bb17f550fff8ee548f2a18cd18b64 Mon Sep 17 00:00:00 2001
From: Stan Hu <stanhu@gmail.com>
Date: Fri, 1 Jul 2016 12:51:21 -0700
Subject: [PATCH] Add support for using RequestStore within Sidekiq tasks via
 SIDEKIQ_REQUEST_STORE env variable

This significantly reduces the DB churn in the PostReceive task when it
performs reference extraction.

See #18663
---
 CHANGELOG                                           |  1 +
 config/initializers/sidekiq.rb                      |  1 +
 .../sidekiq_middleware/request_store_middleware.rb  | 13 +++++++++++++
 3 files changed, 15 insertions(+)
 create mode 100644 lib/gitlab/sidekiq_middleware/request_store_middleware.rb

diff --git a/CHANGELOG b/CHANGELOG
index 534f57cb08e..0b796cc66a1 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -4,6 +4,7 @@ v 8.11.0 (unreleased)
   - Remove magic comments (`# encoding: UTF-8`) from Ruby files !5456 (winniehell)
   - Fix CI status icon link underline (ClemMakesApps)
   - Fix of 'Commits being passed to custom hooks are already reachable when using the UI'
+  - Add support for using RequestStore within Sidekiq tasks via SIDEKIQ_REQUEST_STORE env variable
   - Limit git rev-list output count to one in forced push check
   - Add green outline to New Branch button !5447 (winniehell)
   - Retrieve rendered HTML from cache in one request
diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb
index 5e839327e7a..48b6075ba78 100644
--- a/config/initializers/sidekiq.rb
+++ b/config/initializers/sidekiq.rb
@@ -7,6 +7,7 @@ Sidekiq.configure_server do |config|
   config.server_middleware do |chain|
     chain.add Gitlab::SidekiqMiddleware::ArgumentsLogger if ENV['SIDEKIQ_LOG_ARGUMENTS']
     chain.add Gitlab::SidekiqMiddleware::MemoryKiller if ENV['SIDEKIQ_MEMORY_KILLER_MAX_RSS']
+    chain.add Gitlab::SidekiqMiddleware::RequestStoreMiddleware if ENV['SIDEKIQ_REQUEST_STORE']
   end
 
   # Sidekiq-cron: load recurring jobs from gitlab.yml
diff --git a/lib/gitlab/sidekiq_middleware/request_store_middleware.rb b/lib/gitlab/sidekiq_middleware/request_store_middleware.rb
new file mode 100644
index 00000000000..b1fa0e3cb4e
--- /dev/null
+++ b/lib/gitlab/sidekiq_middleware/request_store_middleware.rb
@@ -0,0 +1,13 @@
+module Gitlab
+  module SidekiqMiddleware
+    class RequestStoreMiddleware
+      def call(worker, job, queue)
+        RequestStore.begin!
+        yield
+      ensure
+        RequestStore.end!
+        RequestStore.clear!
+      end
+    end
+  end
+end
-- 
GitLab