o
    ܀c2                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlm	Z
 ddlmZ ddlmZ ddlmZ dd	lmZmZ d
Zee ZdddZG dd de
Z	G dd dZG dd deZdS )az  Abstractions over S3's upload/download operations.

This module provides high level abstractions for efficient
uploads/downloads.  It handles several things for the user:

* Automatically switching to multipart transfers when
  a file is over a specific size threshold
* Uploading/downloading a file in parallel
* Progress callbacks to monitor transfers
* Retries.  While botocore handles retries for streaming uploads,
  it is not possible for it to handle retries for streaming
  downloads.  This module handles retries for both cases so
  you don't need to implement any retry logic yourself.

This module has a reasonable set of defaults.  It also allows you
to configure many aspects of the transfer process including:

* Multipart threshold size
* Max parallel downloads
* Socket timeouts
* Retry amounts

There is no support for s3->s3 multipart copies at this
time.


.. _ref_s3transfer_usage:

Usage
=====

The simplest way to use this module is:

.. code-block:: python

    client = boto3.client('s3', 'us-west-2')
    transfer = S3Transfer(client)
    # Upload /tmp/myfile to s3://bucket/key
    transfer.upload_file('/tmp/myfile', 'bucket', 'key')

    # Download s3://bucket/key to /tmp/myfile
    transfer.download_file('bucket', 'key', '/tmp/myfile')

The ``upload_file`` and ``download_file`` methods also accept
``**kwargs``, which will be forwarded through to the corresponding
client operation.  Here are a few examples using ``upload_file``::

    # Making the object public
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         extra_args={'ACL': 'public-read'})

    # Setting metadata
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         extra_args={'Metadata': {'a': 'b', 'c': 'd'}})

    # Setting content type
    transfer.upload_file('/tmp/myfile.json', 'bucket', 'key',
                         extra_args={'ContentType': "application/json"})


The ``S3Transfer`` class also supports progress callbacks so you can
provide transfer progress to users.  Both the ``upload_file`` and
``download_file`` methods take an optional ``callback`` parameter.
Here's an example of how to print a simple progress percentage
to the user:

.. code-block:: python

    class ProgressPercentage(object):
        def __init__(self, filename):
            self._filename = filename
            self._size = float(os.path.getsize(filename))
            self._seen_so_far = 0
            self._lock = threading.Lock()

        def __call__(self, bytes_amount):
            # To simplify we'll assume this is hooked up
            # to a single filename.
            with self._lock:
                self._seen_so_far += bytes_amount
                percentage = (self._seen_so_far / self._size) * 100
                sys.stdout.write(
                    "%s  %s / %s  (%.2f%%)" % (
                        self._filename, self._seen_so_far, self._size,
                        percentage))
                sys.stdout.flush()


    transfer = S3Transfer(boto3.client('s3', 'us-west-2'))
    # Upload /tmp/myfile to s3://bucket/key and print upload progress.
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         callback=ProgressPercentage('/tmp/myfile'))



You can also provide a TransferConfig object to the S3Transfer
object that gives you more fine grained control over the
transfer.  For example:

.. code-block:: python

    client = boto3.client('s3', 'us-west-2')
    config = TransferConfig(
        multipart_threshold=8 * 1024 * 1024,
        max_concurrency=10,
        num_download_attempts=10,
    )
    transfer = S3Transfer(client, config)
    transfer.upload_file('/tmp/foo', 'bucket', 'key')


    )ClientError)RetriesExceededError)NonThreadedExecutor)TransferConfig)TransferManager)BaseSubscriber)OSUtils)r   S3UploadFailedErrori   Nc                 C   s   d}|j st}t| |||S )a  Creates a transfer manager based on configuration

    :type client: boto3.client
    :param client: The S3 client to use

    :type config: boto3.s3.transfer.TransferConfig
    :param config: The transfer config to use

    :type osutil: s3transfer.utils.OSUtils
    :param osutil: The os utility to use

    :rtype: s3transfer.manager.TransferManager
    :returns: A transfer manager based on parameters provided
    N)use_threadsr   r   )clientconfigosutilexecutor_cls r   </usr/local/lib/python3.10/dist-packages/boto3/s3/transfer.pycreate_transfer_manager   s   r   c                       sP   e Zd ZdddZde dde ddde d	d
f fdd	Z fddZ  ZS )r   max_request_concurrencymax_io_queue_size)max_concurrencymax_io_queue   
      d      TNc	           
   	      sH   t  j|||||||d | jD ]}	t| |	t| | j|	  q|| _dS )a  Configuration object for managed S3 transfers

        :param multipart_threshold: The transfer size threshold for which
            multipart uploads, downloads, and copies will automatically be
            triggered.

        :param max_concurrency: The maximum number of threads that will be
            making requests to perform a transfer. If ``use_threads`` is
            set to ``False``, the value provided is ignored as the transfer
            will only ever use the main thread.

        :param multipart_chunksize: The partition size of each part for a
            multipart transfer.

        :param num_download_attempts: The number of download attempts that
            will be retried upon errors with downloading an object in S3.
            Note that these retries account for errors that occur when
            streaming  down the data from s3 (i.e. socket errors and read
            timeouts that occur after receiving an OK response from s3).
            Other retryable exceptions such as throttling errors and 5xx
            errors are already retried by botocore (this default is 5). This
            does not take into account the number of exceptions retried by
            botocore.

        :param max_io_queue: The maximum amount of read parts that can be
            queued in memory to be written for a download. The size of each
            of these read parts is at most the size of ``io_chunksize``.

        :param io_chunksize: The max size of each chunk in the io queue.
            Currently, this is size used when ``read`` is called on the
            downloaded stream as well.

        :param use_threads: If True, threads will be used when performing
            S3 transfers. If False, no threads will be used in
            performing transfers; all logic will be run in the main thread.

        :param max_bandwidth: The maximum bandwidth that will be consumed
            in uploading and downloading file content. The value is an integer
            in terms of bytes per second.
        )multipart_thresholdr   multipart_chunksizenum_download_attemptsr   io_chunksizemax_bandwidthN)super__init__ALIASsetattrgetattrr
   )
selfr   r   r   r   r   r   r
   r   alias	__class__r   r   r!      s   3

zTransferConfig.__init__c                    s0   || j v rt | j | | t || d S N)r"   r    __setattr__)r%   namevaluer'   r   r   r*      s   
zTransferConfig.__setattr__)	__name__
__module____qualname__r"   MBKBr!   r*   __classcell__r   r   r'   r   r      s    Cr   c                   @   sR   e Zd ZejZejZdddZ	dddZ	dddZdd	 Z	d
d Z
dd ZdS )
S3TransferNc                 C   sf   |s|st d|rt|||grt d|d u rt }|d u r#t }|r*|| _d S t|||| _d S )NzLEither a boto3.Client or s3transfer.manager.TransferManager must be providedzdManager cannot be provided with client, config, nor osutil. These parameters are mutually exclusive.)
ValueErroranyr   r   _managerr   )r%   r   r   r   managerr   r   r   r!      s   
zS3Transfer.__init__c           	      C   st   t |ts	td| |}| j|||||}z|  W dS  ty9 } ztd	|d
||g|d}~ww )a(  Upload a file to an S3 object.

        Variants have also been injected into S3 client, Bucket and Object.
        You don't have to use S3Transfer.upload_file() directly.

        .. seealso::
            :py:meth:`S3.Client.upload_file`
            :py:meth:`S3.Client.upload_fileobj`
        Filename must be a stringzFailed to upload {} to {}: {}/N)
isinstancestrr4   _get_subscribersr6   uploadresultr   r	   formatjoin)	r%   filenamebucketkeycallback
extra_argssubscribersfutureer   r   r   upload_file  s    


zS3Transfer.upload_filec           	   
   C   sb   t |ts	td| |}| j|||||}z|  W dS  ty0 } zt|j	d}~ww )a0  Download an S3 object to a file.

        Variants have also been injected into S3 client, Bucket and Object.
        You don't have to use S3Transfer.download_file() directly.

        .. seealso::
            :py:meth:`S3.Client.download_file`
            :py:meth:`S3.Client.download_fileobj`
        r8   N)
r:   r;   r4   r<   r6   downloadr>   S3TransferRetriesExceededErrorr   last_exception)	r%   rB   rC   rA   rE   rD   rF   rG   rH   r   r   r   download_file,  s   



zS3Transfer.download_filec                 C   s   |sd S t |gS r)   )ProgressCallbackInvokerr%   rD   r   r   r   r<   I  s   
zS3Transfer._get_subscribersc                 C   s   | S r)   r   )r%   r   r   r   	__enter__N  s   zS3Transfer.__enter__c                 G   s   | j j|  d S r)   )r6   __exit__)r%   argsr   r   r   rQ   Q  s   zS3Transfer.__exit__)NNNN)NN)r-   r.   r/   r   ALLOWED_DOWNLOAD_ARGSALLOWED_UPLOAD_ARGSr!   rI   rM   r<   rP   rQ   r   r   r   r   r3      s    

!
r3   c                   @   s    e Zd ZdZdd Zdd ZdS )rN   zA back-compat wrapper to invoke a provided callback via a subscriber

    :param callback: A callable that takes a single positional argument for
        how many bytes were transferred.
    c                 C   s
   || _ d S r)   	_callbackrO   r   r   r   r!   \  s   
z ProgressCallbackInvoker.__init__c                 K   s   |  | d S r)   rU   )r%   bytes_transferredkwargsr   r   r   on_progress_  s   z#ProgressCallbackInvoker.on_progressN)r-   r.   r/   __doc__r!   rY   r   r   r   r   rN   U  s    rN   r)   )rZ   botocore.exceptionsr   s3transfer.exceptionsr   rK   s3transfer.futuresr   s3transfer.managerr   S3TransferConfigr   s3transfer.subscribersr   s3transfer.utilsr   boto3.exceptionsr	   r1   r0   r   r3   rN   r   r   r   r   <module>   s   p
Ra