# frozen_string_literal: true

# Copyright (C) 2015-2023 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

module Mongo
  module Retryable
    # The abstract superclass for workers employed by Mongo::Retryable.
    #
    # @api private
    class BaseWorker
      extend Forwardable

      def_delegators :retryable,
                     :client,
                     :cluster,
                     :select_server

      # @return [ Mongo::Retryable ] retryable A reference to the client object
      #   that instantiated this worker.
      attr_reader :retryable

      # Constructs a new worker.
      #
      # @example Instantiating a new read worker
      #   worker = Mongo::Retryable::ReadWorker.new(self)
      #
      # @example Instantiating a new write worker
      #   worker = Mongo::Retryable::WriteWorker.new(self)
      #
      # @param [ Mongo::Retryable ] retryable The client object that is using
      #   this worker to perform a retryable operation
      def initialize(retryable)
        @retryable = retryable
      end

      private

      # Indicate which exception classes that are generally retryable
      # when using modern retries mechanism.
      #
      # @return [ Array<Mongo:Error> ] Array of exception classes that are
      #   considered retryable.
      def retryable_exceptions
        [
          Error::ConnectionPerished,
          Error::ServerNotUsable,
          Error::SocketError,
          Error::SocketTimeoutError,
        ].freeze
      end

      # Indicate which exception classes that are generally retryable
      # when using legacy retries mechanism.
      #
      # @return [ Array<Mongo:Error> ] Array of exception classes that are
      #   considered retryable.
      def legacy_retryable_exceptions
        [
          Error::ConnectionPerished,
          Error::ServerNotUsable,
          Error::SocketError,
          Error::SocketTimeoutError,
          Error::PoolClearedError,
          Error::PoolPausedError,
        ].freeze
      end

      # Tests to see if the given exception instance is of a type that can
      # be retried with modern retry mechanism.
      #
      # @return [ true | false ] true if the exception is retryable.
      def is_retryable_exception?(e)
        retryable_exceptions.any? { |klass| klass === e }
      end

      # Tests to see if the given exception instance is of a type that can
      # be retried with legacy retry mechanism.
      #
      # @return [ true | false ] true if the exception is retryable.
      def is_legacy_retryable_exception?(e)
        legacy_retryable_exceptions.any? { |klass| klass === e }
      end

      # Logs the given deprecation warning the first time it is called for a
      # given key; after that, it does nothing when given the same key.
      def deprecation_warning(key, warning)
        $_deprecation_warnings ||= {}
        return if $_deprecation_warnings[key]

        $_deprecation_warnings[key] = true
        Logger.logger.warn(warning)
      end

      # Log a warning so that any application slow down is immediately obvious.
      def log_retry(e, options = nil)
        message = (options || {}).fetch(:message, 'Retry')
        Logger.logger.warn "#{message} due to: #{e.class.name}: #{e.message}"
      end

      # Returns the retry policy from the client.
      #
      # @return [ Mongo::Retryable::RetryPolicy ] The retry policy.
      def retry_policy
        client.retry_policy
      end

      # Whether the error indicates server overload.
      #
      # @param [ Exception ] e The error to check.
      #
      # @return [ true | false ] true if the error has the
      #   SystemOverloadedError label.
      def overload_error?(e)
        e.respond_to?(:label?) && e.label?('SystemOverloadedError')
      end

      # Whether the error is a retryable overload error. An error is
      # retryable overload when it has both the SystemOverloadedError and
      # RetryableError labels.
      #
      # @param [ Exception ] e The error to check.
      #
      # @return [ true | false ] true if the error has both labels.
      def retryable_overload_error?(e)
        overload_error?(e) &&
          e.respond_to?(:label?) && e.label?('RetryableError')
      end
    end
  end
end
