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

require 'English'

# This must precede other Contrast C extensions
require 'cs__common/cs__common'
# This must precede any patching we do as we log patches and we shouldn't cause
# requires to happen during that process.
require 'contrast/components/logger'

# defining instrumentation, this must precede core extensions
# because they need to register their patches
require 'contrast/agent/patching/policy/patcher'
require 'contrast/agent/patching/policy/patch'

# core extensions
require 'contrast/extension/assess'
require 'contrast/extension/delegator'
require 'contrast/extension/inventory'
require 'contrast/extension/module'
require 'contrast/extension/protect'

require 'contrast/utils/object_share'
require 'contrast/utils/string_utils'
require 'contrast/utils/io_util'
require 'contrast/utils/os'

require 'contrast/utils/hash_digest'
require 'contrast/utils/invalid_configuration_util'

# scoping
require 'contrast/agent/scope'

require 'contrast/utils/thread_tracker'

# Framework support
require 'contrast/framework/manager'

# Communication to SR
require 'contrast/api/communication'

require 'contrast/agent/thread_watcher'

module Contrast
  # Top namespace of the Agent section. Holds tracking contexts that will be
  # accessed throughout the Agent.
  module Agent
    # build a map for tracking the context of the current request
    REQUEST_TRACKER = Contrast::Utils::ThreadTracker.new

    def self.framework_manager
      @_framework_manager ||= Contrast::Framework::Manager.new
    end

    def self.heapdump_util
      thread_watcher.heapdump_util
    end

    def self.messaging_queue
      thread_watcher.messaging_queue
    end

    def self.telemetry_queue
      return unless thread_watcher.telemetry_queue

      thread_watcher.telemetry_queue
    end

    def self.thread_watcher
      @_thread_watcher ||= Contrast::Agent::ThreadWatcher.new
    end
  end
end

require 'contrast/api'

require 'contrast/utils/resource_loader'
require 'contrast/utils/duck_utils'
require 'contrast/agent/tracepoint_hook'
require 'contrast/agent/at_exit_hook'

# communication with contrast service
require 'contrast/agent/exclusion_matcher'

# threads that handle contrast scope
require 'contrast/agent/thread'

# keep track of attacks
require 'contrast/agent/request_context'

require 'contrast/agent/assess'

# protect rules
require 'contrast/agent/protect/rule'

# application libraries and technologies
require 'contrast/agent/inventory'

# rack event monitoring
require 'contrast/agent/middleware'

# Install the patches we need before the application has a chance to initialize
Contrast::Agent.framework_manager.before_load_patches!