1# frozen_string_literal: true
2
3module Gitlab
4  module SafeRequestStore
5    NULL_STORE = Gitlab::NullRequestStore.new
6
7    class << self
8      # These methods should always run directly against RequestStore
9      delegate :clear!, :begin!, :end!, :active?, to: :RequestStore
10
11      # These methods will run against NullRequestStore if RequestStore is disabled
12      delegate :read, :[], :write, :[]=, :exist?, :fetch, :delete, to: :store
13    end
14
15    def self.store
16      if RequestStore.active?
17        RequestStore
18      else
19        NULL_STORE
20      end
21    end
22
23    # Access to the backing storage of the request store. This returns an object
24    # with `[]` and `[]=` methods that does not discard values.
25    #
26    # This can be useful if storage is needed for a delimited purpose, and the
27    # forgetful nature of the null store is undesirable.
28    def self.storage
29      store.store
30    end
31
32    # This method accept an options hash to be compatible with
33    # ActiveSupport::Cache::Store#write method. The options are
34    # not passed to the underlying cache implementation because
35    # RequestStore#write accepts only a key, and value params.
36    def self.write(key, value, options = nil)
37      store.write(key, value)
38    end
39
40    def self.delete_if(&block)
41      return unless RequestStore.active?
42
43      storage.delete_if { |k, v| block.call(k) }
44    end
45  end
46end
47