Sha256: ec592d7ddb8dbf4b2d1a976bbe6818fc8734207e8846464f444716a00429c5a6

Contents?: true

Size: 1.29 KB

Versions: 7

Compression:

Stored size: 1.29 KB

Contents

# Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

module Contrast
  module Utils
    # ThreadTracker allows tracking of singleton objects across threads
    class ThreadTracker
      def initialize logger = nil
        @logger = logger
      end

      # Note about Ruby -- thread#[] is fiber-local,
      # #thread_variables is not.

      def get key, default = nil
        log(key)
        Thread.current[key] || default
      end

      def set key, value
        Thread.current[key] = value
      end

      def delete key
        Thread.current[key] = nil
      end

      def lifespan obj
        set(:current_context, obj)
        response = yield(obj)
        delete(:current_context)
        response
      end

      def current
        get(:current_context)
      end

      def update_current_context context
        set(:current_context, context)
      end

      # logger may be nil so use this utility method instead
      def log key, msg = nil
        return unless @logger
        return unless @logger.debug?

        @logger.debug("Thread Tracker[#{ key }] :: #{ Process.pid }.#{ Thread.current.object_id } => #{ msg }")
      rescue StandardError
        false # NOOP
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
contrast-agent-3.10.2 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.10.1 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.10.0 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.9.1 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.9.0 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.8.5 lib/contrast/utils/thread_tracker.rb
contrast-agent-3.8.4 lib/contrast/utils/thread_tracker.rb