o
    ܀cn                     @   s   d dl Z d dlZd dlZd dlZd dlmZmZ d dlmZm	Z	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 dlmZmZmZmZmZmZ d d	lmZ d d
lmZmZm Z m!Z!m"Z"m#Z#m$Z$ e%e&Z'G dd dZ(G dd dZ)G dd dZ*dS )    N)BandwidthLimiterLeakyBucket)ALLOWED_DOWNLOAD_ARGSKBMB)CopySubmissionTask)DeleteSubmissionTask)DownloadSubmissionTask)CancelledError
FatalError)IN_MEMORY_DOWNLOAD_TAGIN_MEMORY_UPLOAD_TAGBoundedExecutorTransferCoordinatorTransferFutureTransferMeta)UploadSubmissionTask)CallArgsOSUtilsSlidingWindowSemaphoreTaskSemaphoreget_callbackssignal_not_transferringsignal_transferringc                   @   sB   e Zd Zde de dddddde ddddfddZd	d
 ZdS )TransferConfig   
      i     Nc                 C   sT   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _|   dS )as  Configurations for the transfer manager

        :param multipart_threshold: The threshold for which multipart
            transfers occur.

        :param max_request_concurrency: The maximum number of S3 API
            transfer-related requests that can happen at a time.

        :param max_submission_concurrency: The maximum number of threads
            processing a call to a TransferManager method. Processing a
            call usually entails determining which S3 API requests that need
            to be enqueued, but does **not** entail making any of the
            S3 API data transferring requests needed to perform the transfer.
            The threads controlled by ``max_request_concurrency`` is
            responsible for that.

        :param multipart_chunksize: The size of each transfer if a request
            becomes a multipart transfer.

        :param max_request_queue_size: The maximum amount of S3 API requests
            that can be queued at a time.

        :param max_submission_queue_size: The maximum amount of
            TransferManager method calls that can be queued at a time.

        :param max_io_queue_size: The maximum amount of read parts that
            can be queued to be written to disk per download. The default
            size for each elementin this queue is 8 KB.

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

        :param num_download_attempts: The number of download attempts that
            will be tried 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). The
            ``num_download_attempts`` does not take into account the
            number of exceptions retried by botocore.

        :param max_in_memory_upload_chunks: The number of chunks that can
            be stored in memory at a time for all ongoing upload requests.
            This pertains to chunks of data that need to be stored in memory
            during an upload if the data is sourced from a file-like object.
            The total maximum memory footprint due to a in-memory upload
            chunks is roughly equal to:

                max_in_memory_upload_chunks * multipart_chunksize
                + max_submission_concurrency * multipart_chunksize

            ``max_submission_concurrency`` has an affect on this value because
            for each thread pulling data off of a file-like object, they may
            be waiting with a single read chunk to be submitted for upload
            because the ``max_in_memory_upload_chunks`` value has been reached
            by the threads making the upload request.

        :param max_in_memory_download_chunks: The number of chunks that can
            be buffered in memory and **not** in the io queue at a time for all
            ongoing download requests. This pertains specifically to file-like
            objects that cannot be seeked. The total maximum memory footprint
            due to a in-memory download chunks is roughly equal to:

                max_in_memory_download_chunks * multipart_chunksize

        :param max_bandwidth: The maximum bandwidth that will be consumed
            in uploading and downloading file content. The value is in terms of
            bytes per second.
        N)multipart_thresholdmultipart_chunksizemax_request_concurrencymax_submission_concurrencymax_request_queue_sizemax_submission_queue_sizemax_io_queue_sizeio_chunksizenum_download_attemptsmax_in_memory_upload_chunksmax_in_memory_download_chunksmax_bandwidth_validate_attrs_are_nonzero)selfr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*    r-   =/usr/local/lib/python3.10/dist-packages/s3transfer/manager.py__init__/   s   VzTransferConfig.__init__c                 C   s8   | j  D ]\}}|d ur|dkrtd||f qd S )Nr   z9Provided parameter %s of value %s must be greater than 0.)__dict__items
ValueError)r,   attrattr_valr-   r-   r.   r+      s   z*TransferConfig._validate_attrs_are_nonzero)__name__
__module____qualname__r   r   r/   r+   r-   r-   r-   r.   r   .   s    
dr   c                   @   s   e Zd ZeZg dZeg d Zg dZdZde	diZ
d,dd	Zed
d Zedd Zd-ddZ	d-ddZ			d,ddZd-ddZdd Zdd Z	d.ddZdd Zdd Zd d! Zd"d# Zd$d% Zd/d(d)Zefd*d+ZdS )0TransferManager)ACLCacheControlChecksumAlgorithmContentDispositionContentEncodingContentLanguageContentTypeExpectedBucketOwnerExpiresGrantFullControl	GrantReadGrantReadACPGrantWriteACPMetadataObjectLockLegalHoldStatusObjectLockModeObjectLockRetainUntilDateRequestPayerServerSideEncryptionStorageClassSSECustomerAlgorithmSSECustomerKeySSECustomerKeyMD5SSEKMSKeyIdSSEKMSEncryptionContextTaggingWebsiteRedirectLocation)	CopySourceIfMatchCopySourceIfModifiedSinceCopySourceIfNoneMatchCopySourceIfUnmodifiedSinceCopySourceSSECustomerAlgorithmCopySourceSSECustomerKeyCopySourceSSECustomerKeyMD5MetadataDirectiveTaggingDirective)MFA	VersionIdrJ   r@   TzS3 Object LambdazV^arn:(aws).*:s3-object-lambda:[a-z\-0-9]+:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\-]{1,63}Nc                 C   s   || _ || _|du rt | _|| _|du rt | _t | _d| _t| jj	| jj
tt| jjtt| jji|d| _t| jj| jj|d| _t| jjd|d| _d| _| jjdurktd| jj t| jj}t|| _|   dS )a  A transfer manager interface for Amazon S3

        :param client: Client to be used by the manager
        :param config: TransferConfig to associate specific configurations
        :param osutil: OSUtils object to use for os-related behavior when
            using with transfer manager.

        :type executor_cls: s3transfer.futures.BaseExecutor
        :param executor_cls: The class of executor to use with the transfer
            manager. By default, concurrent.futures.ThreadPoolExecutor is used.
        Nr   )max_sizemax_num_threadstag_semaphoresexecutor_cls)r_   r`   rb      zSetting max_bandwidth to %s)_client_configr   _osutilr   TransferCoordinatorController_coordinator_controller_id_counterr   r#   r!   r   r   r(   r   r   r)   _request_executorr$   r"   _submission_executorr%   _io_executor_bandwidth_limiterr*   loggerdebugr   r   _register_handlers)r,   clientconfigosutilrb   leaky_bucketr-   r-   r.   r/      sN   
zTransferManager.__init__c                 C      | j S N)rd   r,   r-   r-   r.   rq        zTransferManager.clientc                 C   ru   rv   )re   rw   r-   r-   r.   rr     rx   zTransferManager.configc                 C   sd   |du ri }|du rg }|  || j | | t|||||d}i }| jr+| j|d< | |t|S )a  Uploads a file to S3

        :type fileobj: str or seekable file-like object
        :param fileobj: The name of a file to upload or a seekable file-like
            object to upload. It is recommended to use a filename because
            file-like objects may result in higher memory usage.

        :type bucket: str
        :param bucket: The name of the bucket to upload to

        :type key: str
        :param key: The name of the key to upload to

        :type extra_args: dict
        :param extra_args: Extra arguments that may be passed to the
            client operation

        :type subscribers: list(s3transfer.subscribers.BaseSubscriber)
        :param subscribers: The list of subscribers to be invoked in the
            order provided based on the event emit during the process of
            the transfer request.

        :rtype: s3transfer.futures.TransferFuture
        :returns: Transfer future representing the upload
        N)fileobjbucketkey
extra_argssubscribersbandwidth_limiter)_validate_all_known_argsALLOWED_UPLOAD_ARGS_validate_if_bucket_supportedr   rm   _submit_transferr   )r,   ry   rz   r{   r|   r}   	call_argsextra_main_kwargsr-   r-   r.   upload#  s&   

zTransferManager.uploadc                 C   sj   |du ri }|du rg }|  || j | | t|||||d}d| ji}| jr.| j|d< | |t|S )a  Downloads a file from S3

        :type bucket: str
        :param bucket: The name of the bucket to download from

        :type key: str
        :param key: The name of the key to download from

        :type fileobj: str or seekable file-like object
        :param fileobj: The name of a file to download or a seekable file-like
            object to download. It is recommended to use a filename because
            file-like objects may result in higher memory usage.

        :type extra_args: dict
        :param extra_args: Extra arguments that may be passed to the
            client operation

        :type subscribers: list(s3transfer.subscribers.BaseSubscriber)
        :param subscribers: The list of subscribers to be invoked in the
            order provided based on the event emit during the process of
            the transfer request.

        :rtype: s3transfer.futures.TransferFuture
        :returns: Transfer future representing the download
        N)rz   r{   ry   r|   r}   io_executorr~   )r   r   r   r   rl   rm   r   r	   )r,   rz   r{   ry   r|   r}   r   r   r-   r-   r.   downloadQ  s&   


zTransferManager.downloadc                 C   sx   |du ri }|du rg }|du r| j }| || j t|tr'| |d | | t||||||d}| |t	S )a  Copies a file in S3

        :type copy_source: dict
        :param copy_source: The name of the source bucket, key name of the
            source object, and optional version ID of the source object. The
            dictionary format is:
            ``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note
            that the ``VersionId`` key is optional and may be omitted.

        :type bucket: str
        :param bucket: The name of the bucket to copy to

        :type key: str
        :param key: The name of the key to copy to

        :type extra_args: dict
        :param extra_args: Extra arguments that may be passed to the
            client operation

        :type subscribers: a list of subscribers
        :param subscribers: The list of subscribers to be invoked in the
            order provided based on the event emit during the process of
            the transfer request.

        :type source_client: botocore or boto3 Client
        :param source_client: The client to be used for operation that
            may happen at the source object. For example, this client is
            used for the head_object that determines the size of the copy.
            If no client is provided, the transfer manager's client is used
            as the client for the source object.

        :rtype: s3transfer.futures.TransferFuture
        :returns: Transfer future representing the copy
        NBucket)copy_sourcerz   r{   r|   r}   source_client)
rd   r   ALLOWED_COPY_ARGS
isinstancedictr   getr   r   r   )r,   r   rz   r{   r|   r}   r   r   r-   r-   r.   copy  s&   +

zTransferManager.copyc                 C   sL   |du ri }|du rg }|  || j | | t||||d}| |tS )a  Delete an S3 object.

        :type bucket: str
        :param bucket: The name of the bucket.

        :type key: str
        :param key: The name of the S3 object to delete.

        :type extra_args: dict
        :param extra_args: Extra arguments that may be passed to the
            DeleteObject call.

        :type subscribers: list
        :param subscribers: A list of subscribers to be invoked during the
            process of the transfer request.  Note that the ``on_progress``
            callback is not invoked during object deletion.

        :rtype: s3transfer.futures.TransferFuture
        :return: Transfer future representing the deletion.

        N)rz   r{   r|   r}   )r   ALLOWED_DELETE_ARGSr   r   r   r   )r,   rz   r{   r|   r}   r   r-   r-   r.   delete  s   
zTransferManager.deletec                 C   s<   | j r| j D ]\}}||}|rtd| qd S d S )NzTTransferManager methods do not support %s resource. Use direct client calls instead.) VALIDATE_SUPPORTED_BUCKET_VALUES_UNSUPPORTED_BUCKET_PATTERNSr1   matchr2   )r,   rz   resourcepatternr   r-   r-   r.   r     s   
z-TransferManager._validate_if_bucket_supportedc                 C   s,   |D ]}||vrt d|d|f qd S )Nz/Invalid extra_args key '%s', must be one of: %sz, )r2   join)r,   actualallowedkwargr-   r-   r.   r     s   z(TransferManager._validate_all_known_argsc                 C   sj   |si }|  |\}}t|dD ]	}|d | q| ||}| j||d |d |  jd7  _|S )Ndonecoordinator)transfer_coordinatormain_kwargsrc   )_get_future_with_componentsr   add_done_callback _get_submission_task_main_kwargsrk   submitri   )r,   r   submission_task_clsr   transfer_future
componentscallbackr   r-   r-   r.   r     s$   z TransferManager._submit_transferc                 C   sT   | j }t|d}| j| || jj| t||d|d}tdi |}||fS )N)transfer_id)metar   r-   )ri   r   rh   add_transfer_coordinatorr   remove_transfer_coordinatorr   r   )r,   r   r   r   r   r   r-   r-   r.   r     s   

z+TransferManager._get_future_with_componentsc                 C   s&   | j | j| j| j|d}|| |S )N)rq   rr   rs   request_executorr   )rd   re   rf   rj   update)r,   r   r   r   r-   r-   r.   r   1  s   
z0TransferManager._get_submission_task_main_kwargsc                 C   s4   d}| j jjj|tdd | j jjj|tdd d S )Nzrequest-created.s3zs3upload-not-transferring)	unique_idzs3upload-transferring)rd   r   eventsregister_firstr   register_lastr   )r,   
event_namer-   r-   r.   rp   >  s   


z"TransferManager._register_handlersc                 C   s   | S rv   r-   rw   r-   r-   r.   	__enter__J  s   zTransferManager.__enter__c                 G   sH   d}d}t }|rd}t|}|st|}t|trt}| ||| d S )NF T)r   strreprr   KeyboardInterruptr
   	_shutdown)r,   exc_type	exc_valueargscancel
cancel_msgcancel_exc_typer-   r-   r.   __exit__M  s   
zTransferManager.__exit__Fr   c                 C   s   |  ||| dS )a  Shutdown the TransferManager

        It will wait till all transfers complete before it completely shuts
        down.

        :type cancel: boolean
        :param cancel: If True, calls TransferFuture.cancel() for
            all in-progress in transfers. This is useful if you want the
            shutdown to happen quicker.

        :type cancel_msg: str
        :param cancel_msg: The message to specify if canceling all in-progress
            transfers.
        N)r   )r,   r   r   r-   r-   r.   shutdown^  s   zTransferManager.shutdownc                 C   s   |r	| j || z(z| j   W n ty   | j d  w W | j  | j  | j  d S | j  | j  | j  w )NzKeyboardInterrupt())rh   r   waitr   rk   r   rj   rl   )r,   r   r   r   r-   r-   r.   r   o  s   



zTransferManager._shutdown)NNN)NNrv   )Fr   )r5   r6   r7   r   r   r   r   r   recompiler   r/   propertyrq   rr   r   r   r   r   r   r   r   r   r   rp   r   r   r   r
   r   r-   r-   r-   r.   r8      sD    
B


/
5

?$	
#
r8   c                   @   sF   e Zd Zdd Zedd Zdd Zdd Zd	efd
dZ	dd Z
dS )rg   c                 C   s   t  | _t | _dS )zAbstraction to control all transfer coordinators

        This abstraction allows the manager to wait for inprogress transfers
        to complete and cancel all inprogress transfers.
        N)	threadingLock_lockset_tracked_transfer_coordinatorsrw   r-   r-   r.   r/     s   
z&TransferCoordinatorController.__init__c                 C   s6   | j  t| jW  d   S 1 sw   Y  dS )z.The set of transfer coordinators being trackedN)r   r   r   rw   r-   r-   r.   tracked_transfer_coordinators  s   
$z;TransferCoordinatorController.tracked_transfer_coordinatorsc                 C   8   | j  | j| W d   dS 1 sw   Y  dS )zAdds a transfer coordinator of a transfer to be canceled if needed

        :type transfer_coordinator: s3transfer.futures.TransferCoordinator
        :param transfer_coordinator: The transfer coordinator for the
            particular transfer
        N)r   r   addr,   r   r-   r-   r.   r     s   "z6TransferCoordinatorController.add_transfer_coordinatorc                 C   r   )a  Remove a transfer coordinator from cancellation consideration

        Typically, this method is invoked by the transfer coordinator itself
        to remove its self when it completes its transfer.

        :type transfer_coordinator: s3transfer.futures.TransferCoordinator
        :param transfer_coordinator: The transfer coordinator for the
            particular transfer
        N)r   r   remover   r-   r-   r.   r     s   
"z9TransferCoordinatorController.remove_transfer_coordinatorr   c                 C   s   | j D ]}||| qdS )aP  Cancels all inprogress transfers

        This cancels the inprogress transfers by calling cancel() on all
        tracked transfer coordinators.

        :param msg: The message to pass on to each transfer coordinator that
            gets cancelled.

        :param exc_type: The type of exception to set for the cancellation
        N)r   r   )r,   msgr   r   r-   r-   r.   r     s   
z$TransferCoordinatorController.cancelc                 C   s\   zd}| j D ]}|  qW dS  ty$   td |r#td|   ty-   Y dS w )zWait until there are no more inprogress transfers

        This will not stop when failures are encountered and not propagate any
        of these errors from failed transfers, but it can be interrupted with
        a KeyboardInterrupt.
        Nz$Received KeyboardInterrupt in wait()z'On KeyboardInterrupt was waiting for %s)r   resultr   rn   ro   	Exceptionr   r-   r-   r.   r     s    


z"TransferCoordinatorController.waitN)r5   r6   r7   r/   r   r   r   r   r
   r   r   r-   r-   r-   r.   rg     s    	

rg   )+r   loggingr   r   s3transfer.bandwidthr   r   s3transfer.constantsr   r   r   s3transfer.copiesr   s3transfer.deleter   s3transfer.downloadr	   s3transfer.exceptionsr
   r   s3transfer.futuresr   r   r   r   r   r   s3transfer.uploadr   s3transfer.utilsr   r   r   r   r   r   r   	getLoggerr5   rn   r   r8   rg   r-   r-   r-   r.   <module>   s(    $

n   o