# frozen_string_literal: true

require 'aws-sdk-resources'

module CarrierWave
  module Storage
    class AWS < Abstract
      def self.connection_cache
        @connection_cache ||= {}
      end

      def self.clear_connection_cache!
        @connection_cache = {}
      end

      def store!(file)
        AWSFile.new(uploader, connection, uploader.store_path).tap do |aws_file|
          aws_file.store(file)
        end
      end

      def retrieve!(identifier)
        AWSFile.new(uploader, connection, uploader.store_path(identifier))
      end

      def connection
        @connection ||= begin
          conn_cache = self.class.connection_cache

          conn_cache[credentials] ||= ::Aws::S3::Resource.new(*credentials)
        end
      end

      def credentials
        [uploader.aws_credentials].compact
      end
    end
  end
end

# frozen_string_literal: true

require 'aws-sdk-resources'

Aws.eager_autoload!(services: ['S3'])

module CarrierWave
  module Storage
    class AWS < Abstract
      def self.connection_cache
        @connection_cache ||= {}
      end

      def self.clear_connection_cache!
        @connection_cache = {}
      end

      def store!(file)
        AWSFile.new(uploader, connection, uploader.store_path).tap do |aws_file|
          aws_file.store(file)
        end
      end

      def retrieve!(identifier)
        AWSFile.new(uploader, connection, uploader.store_path(identifier))
      end

      def connection
        @connection ||= begin
          conn_cache = self.class.connection_cache

          conn_cache[credentials] ||= ::Aws::S3::Resource.new(*credentials)
        end
      end

      def credentials
        [uploader.aws_credentials].compact
      end
    end
  end
end

Use eager_autoload for S3 resource
Use eager_autoload for S3 resource

As explained in the [awsblog][0], aws-sdk is autoloaded to keep the
start time low. That isn't entirely threadsafe and can cause loading
errors in multi threaded systems. To fix this, all of 'S3' is now
eagerly autoloaded.

Fixes #93

[0]: https://ruby.awsblog.com/post/Tx16QY1CI5GVBFT/Threading-with-the-AWS-SDK-for-Ruby
