Sha256: a237d2795c5121ff9fd51d83df170e74db9f7193343095b71f33aa9b2cca2c29

Contents?: true

Size: 1.81 KB

Versions: 10

Compression:

Stored size: 1.81 KB

Contents

# typed: ignore

# Copyright (c) 2015 Sqreen. All Rights Reserved.
# Please refer to our terms for more information: https://www.sqreen.com/terms.html

require 'sqreen/ecosystem/loggable'

module Sqreen
  module Ecosystem
    # The transaction storage is a mechanism for the modules to share
    # request-scoped data with each other or to keep request-scoped objects
    # themselves, although, for this last use case to be effective,
    # propagation of request start/end events to the modules will likely be
    # needed. A more generic notification of data availability to modules
    # also may be needed in the future.
    #
    # This is not be used to share data with the Ecosystem client
    #
    # This class is not thread safe because it can call the lazy getter
    # twice if [] is called concurrently.
    class TransactionStorage
      include Loggable

      class << self
        # @return [Sqreen::Ecosystem::TransactionStorage]
        def create_thread_local
          Thread.current[:tx_storage] = new
        end

        # @return [Sqreen::Ecosystem::TransactionStorage]
        def fetch_thread_local
          Thread.current[:tx_storage]
        end

        def destroy_thread_local
          Thread.current[:tx_storage] = nil
        end
      end

      def initialize
        @values = {}
        @values_lazy = {}
      end

      def []=(key, value)
        @values[key] = value
      end

      def set_lazy(key, &block)
        @values_lazy[key] = block
      end

      def [](key)
        v = @values[key]
        return v unless v.nil?

        v = @values_lazy[key]
        return nil if v.nil?

        begin
          @values[key] = v.call
        rescue StandardError => e
          logger.warn { "Error resolving key #{e} with lazy value: #{e.message}" }
          raise
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
sqreen-1.25.1 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.25.0 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.24.3 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.24.2 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.24.1 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.24.0 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.23.2 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.23.1 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.23.0 lib/sqreen/ecosystem/transaction_storage.rb
sqreen-1.22.1 lib/sqreen/ecosystem/transaction_storage.rb