o
    ܀cR                     @   s   d dl Z d dlZd dlZd dl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 eeZG dd dZG d	d
 d
ZG dd deZG dd deZG dd dZG dd dZG dd dZG dd dZG dd deZG dd dZeddgZedZedZdS )    N)
namedtuple)futures)MAXINT)CancelledErrorTransferNotDoneError)FunctionContainerTaskSemaphorec                   @   s0   e Zd Zedd Zdd Zdd Zdd Zd	S )
BaseTransferFuturec                 C      t d)z-The metadata associated to the TransferFuturemetaNotImplementedErrorself r   =/usr/local/lib/python3.10/dist-packages/s3transfer/futures.pyr         zBaseTransferFuture.metac                 C   r
   )zmDetermines if a TransferFuture has completed

        :returns: True if completed. False, otherwise.
        zdone()r   r   r   r   r   done!   s   zBaseTransferFuture.donec                 C   r
   )Waits until TransferFuture is done and returns the result

        If the TransferFuture succeeded, it will return the result. If the
        TransferFuture failed, it will raise the exception associated to the
        failure.
        zresult()r   r   r   r   r   result(   s   zBaseTransferFuture.resultc                 C   r
   )z6Cancels the request associated with the TransferFuturezcancel()r   r   r   r   r   cancel1   s   zBaseTransferFuture.cancelN)__name__
__module____qualname__propertyr   r   r   r   r   r   r   r   r	      s    
	r	   c                   @   s0   e Zd Zedd Zedd Zedd ZdS )BaseTransferMetac                 C   r
   )*The call args used in the transfer request	call_argsr   r   r   r   r   r   7   r   zBaseTransferMeta.call_argsc                 C   r
   )The unique id of the transfertransfer_idr   r   r   r   r   r   <   r   zBaseTransferMeta.transfer_idc                 C   r
   ).A dictionary that requesters can store data inuser_contextr   r   r   r   r   r!   A   r   zBaseTransferMeta.user_contextN)r   r   r   r   r   r   r!   r   r   r   r   r   6   s    

r   c                   @   sB   e Zd ZdddZedd Zdd Zdd	 Zd
d Zdd Z	dS )TransferFutureNc                 C   s4   || _ |du rt | _ || _|du rt | _dS dS )a  The future associated to a submitted transfer request

        :type meta: TransferMeta
        :param meta: The metadata associated to the request. This object
            is visible to the requester.

        :type coordinator: TransferCoordinator
        :param coordinator: The coordinator associated to the request. This
            object is not visible to the requester.
        N)_metaTransferMeta_coordinatorTransferCoordinator)r   r   coordinatorr   r   r   __init__H   s   zTransferFuture.__init__c                 C      | j S N)r#   r   r   r   r   r   [      zTransferFuture.metac                 C   
   | j  S r*   )r%   r   r   r   r   r   r   _      
zTransferFuture.donec              
   C   s2   z| j  W S  ty } z|   |d }~ww r*   )r%   r   KeyboardInterruptr   )r   er   r   r   r   b   s   zTransferFuture.resultc                 C   s   | j   d S r*   )r%   r   r   r   r   r   r   l   s   zTransferFuture.cancelc                 C   s$   |   std| jj|dd dS )z!Sets the exception on the future.z?set_exception can only be called once the transfer is complete.T)overrideN)r   r   r%   set_exception)r   	exceptionr   r   r   r1   o   s
   zTransferFuture.set_exceptionNN)
r   r   r   r(   r   r   r   r   r   r1   r   r   r   r   r"   G   s    


r"   c                   @   sR   e Zd ZdZdddZedd Zedd Zed	d
 Zedd Z	dd Z
dS )r$   z'Holds metadata about the TransferFutureNc                 C   s   || _ || _d | _i | _d S r*   )
_call_args_transfer_id_size_user_context)r   r   r   r   r   r   r(   |   s   
zTransferMeta.__init__c                 C   r)   )r   )r4   r   r   r   r   r         zTransferMeta.call_argsc                 C   r)   )r   )r5   r   r   r   r   r      r8   zTransferMeta.transfer_idc                 C   r)   )z)The size of the transfer request if knownr6   r   r   r   r   size   r8   zTransferMeta.sizec                 C   r)   )r    )r7   r   r   r   r   r!      r8   zTransferMeta.user_contextc                 C   
   || _ dS )zA method to provide the size of a transfer request

        By providing this value, the TransferManager will not try to
        call HeadObject or use the use OS to determine the size of the
        transfer.
        Nr9   )r   r:   r   r   r   provide_transfer_size   s   
z"TransferMeta.provide_transfer_sizer3   )r   r   r   __doc__r(   r   r   r   r:   r!   r<   r   r   r   r   r$   y   s    




r$   c                   @   s   e Zd ZdZd5ddZdd Zedd Zed	d
 Zedd Z	edd Z
dd Zd6ddZdd ZdefddZdd Zdd Zdd Zd5dd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 ZdS )7r&   z*A helper class for managing TransferFutureNc                 C   sb   || _ d| _d | _d | _t | _g | _g | _t	 | _
t | _t | _t | _t | _d S )Nnot-started)r   _status_result
_exceptionset_associated_futures_failure_cleanups_done_callbacks	threadingEvent_done_eventLock_lock_associated_futures_lock_done_callbacks_lock_failure_cleanups_lock)r   r   r   r   r   r(      s   



zTransferCoordinator.__init__c                 C   s   d | jj| jS )Nz{}(transfer_id={}))format	__class__r   r   r   r   r   r   __repr__   s   
zTransferCoordinator.__repr__c                 C   r)   r*   )rA   r   r   r   r   r2      r+   zTransferCoordinator.exceptionc                 C   s6   | j  t| jW  d   S 1 sw   Y  dS )zThe list of futures associated to the inprogress TransferFuture

        Once the transfer finishes this list becomes empty as the transfer
        is considered done and there should be no running futures left.
        N)rK   copyrC   r   r   r   r   associated_futures   s   
$z&TransferCoordinator.associated_futuresc                 C   r)   )z;The list of callbacks to call when the TransferFuture fails)rD   r   r   r   r   failure_cleanups   r8   z$TransferCoordinator.failure_cleanupsc                 C   r)   )a  The status of the TransferFuture

        The currently supported states are:
            * not-started - Has yet to start. If in this state, a transfer
              can be canceled immediately and nothing will happen.
            * queued - SubmissionTask is about to submit tasks
            * running - Is inprogress. In-progress as of now means that
              the SubmissionTask that runs the transfer is being executed. So
              there is no guarantee any transfer requests had been made to
              S3 if this state is reached.
            * cancelled - Was cancelled
            * failed - An exception other than CancelledError was thrown
            * success - No exceptions were thrown and is done.
        )r?   r   r   r   r   status   s   zTransferCoordinator.statusc                 C   s>   | j  d| _|| _d| _W d   dS 1 sw   Y  dS )a  Set a result for the TransferFuture

        Implies that the TransferFuture succeeded. This will always set a
        result because it is invoked on the final task where there is only
        ever one final task and it is ran at the very end of a transfer
        process. So if a result is being set for this final task, the transfer
        succeeded even if something came a long and canceled the transfer
        on the final task.
        Nsuccess)rJ   rA   r@   r?   r   r   r   r   r   
set_result   s
   
"zTransferCoordinator.set_resultFc                 C   sT   | j  |  r
|r|| _d| _W d   dS W d   dS 1 s#w   Y  dS )zSet an exception for the TransferFuture

        Implies the TransferFuture failed.

        :param exception: The exception that cause the transfer to fail.
        :param override: If True, override any existing state.
        failedN)rJ   r   rA   r?   )r   r2   r0   r   r   r   r1      s   "z!TransferCoordinator.set_exceptionc                 C   s   | j t | jr| j| jS )r   )rH   waitr   rA   r@   r   r   r   r   r      s   zTransferCoordinator.result c                 C   s   | j ; |  s.d}td| | ||| _| jdkrd}d| _|r6|   W d   dS W d   dS W d   dS 1 sAw   Y  dS )zCancels the TransferFuture

        :param msg: The message to attach to the cancellation
        :param exc_type: The type of exception to set for the cancellation
        Fz%s cancel(%s) calledr>   T	cancelledN)rJ   r   loggerdebugrA   r?   announce_done)r   msgexc_typeshould_announce_doner   r   r   r     s   


"zTransferCoordinator.cancelc                 C      |  d dS )z+Sets the TransferFutrue's status to runningqueuedN_transition_to_non_done_stater   r   r   r   set_status_to_queued     z(TransferCoordinator.set_status_to_queuedc                 C   rb   )z+Sets the TransferFuture's status to runningrunningNrd   r   r   r   r   set_status_to_running"  rg   z)TransferCoordinator.set_status_to_runningc                 C   sL   | j  |  rtd| j|f || _W d    d S 1 sw   Y  d S )Nz=Unable to transition from done state %s to non-done state %s.)rJ   r   RuntimeErrorrT   r?   )r   desired_stater   r   r   re   &  s   "z1TransferCoordinator._transition_to_non_done_statec                 C   sD   t d||| j |j||d}| | |t| j| |S )a  Submits a task to a provided executor

        :type executor: s3transfer.futures.BoundedExecutor
        :param executor: The executor to submit the callable to

        :type task: s3transfer.tasks.Task
        :param task: The task to submit to the executor

        :type tag: s3transfer.futures.TaskTag
        :param tag: A tag to associate to the submitted task

        :rtype: concurrent.futures.Future
        :returns: A future representing the submitted task
        z;Submitting task {} to executor {} for transfer request: {}.)tag)	r\   r]   rN   r   submitadd_associated_futureadd_done_callbackr   remove_associated_future)r   executortaskrl   futurer   r   r   rm   /  s   

zTransferCoordinator.submitc                 C   s
   | j dv S )zDetermines if a TransferFuture has completed

        :returns: False if status is equal to 'failed', 'cancelled', or
            'success'. True, otherwise
        )rX   r[   rU   )rT   r   r   r   r   r   L  s   
zTransferCoordinator.donec                 C   8   | j  | j| W d   dS 1 sw   Y  dS )z6Adds a future to be associated with the TransferFutureN)rK   rC   addr   rs   r   r   r   rn   T     "z)TransferCoordinator.add_associated_futurec                 C   rt   )z4Removes a future's association to the TransferFutureN)rK   rC   removerv   r   r   r   rp   Y  rw   z,TransferCoordinator.remove_associated_futurec                 O   J   | j  | jt|g|R i | W d   dS 1 sw   Y  dS )z7Add a done callback to be invoked when transfer is doneN)rL   rE   appendr   r   functionargskwargsr   r   r   ro   ^  
   "z%TransferCoordinator.add_done_callbackc                 O   ry   )z$Adds a callback to call upon failureN)rM   rD   rz   r   r{   r   r   r   add_failure_cleanupe  r   z'TransferCoordinator.add_failure_cleanupc                 C   s(   | j dkr	|   | j  |   dS )aM  Announce that future is done running and run associated callbacks

        This will run any failure cleanups if the transfer failed if not
        they have not been run, allows the result() to be unblocked, and will
        run any done callbacks associated to the TransferFuture if they have
        not already been ran.
        rU   N)rT   _run_failure_cleanupsrH   rB   _run_done_callbacksr   r   r   r   r^   l  s   

z!TransferCoordinator.announce_donec                 C   s>   | j  | | j g | _W d    d S 1 sw   Y  d S r*   )rL   _run_callbacksrE   r   r   r   r   r   y     "z'TransferCoordinator._run_done_callbacksc                 C   s>   | j  | | j g | _W d    d S 1 sw   Y  d S r*   )rM   r   rS   rD   r   r   r   r   r     r   z)TransferCoordinator._run_failure_cleanupsc                 C   s   |D ]}|  | qd S r*   )_run_callback)r   	callbackscallbackr   r   r   r     s   z"TransferCoordinator._run_callbacksc                 C   s4   z|  W d S  t y   tjd| dd Y d S w )NzException raised in %s.T)exc_info)	Exceptionr\   r]   )r   r   r   r   r   r     s
   z!TransferCoordinator._run_callbackr*   )F)r   r   r   r=   r(   rP   r   r2   rR   rS   rT   rW   r1   r   r   r   rf   ri   re   rm   r   rn   rp   ro   r   r^   r   r   r   r   r   r   r   r   r&      s<    






	r&   c                   @   s2   e Zd ZejZ	d	ddZd
ddZdddZdS )BoundedExecutorNc                 C   s6   || _ |du r
| j}|| j d| _t|| _|| _dS )aF  An executor implementation that has a maximum queued up tasks

        The executor will block if the number of tasks that have been
        submitted and is currently working on is past its maximum.

        :params max_size: The maximum number of inflight futures. An inflight
            future means that the task is either queued up or is currently
            being executed. A size of None or 0 means that the executor will
            have no bound in terms of the number of inflight futures.

        :params max_num_threads: The maximum number of threads the executor
            uses.

        :type tag_semaphores: dict
        :params tag_semaphores: A dictionary where the key is the name of the
            tag and the value is the semaphore to use when limiting the
            number of tasks the executor is processing at a time.

        :type executor_cls: BaseExecutor
        :param underlying_executor_cls: The executor class that
            get bounded by this executor. If None is provided, the
            concurrent.futures.ThreadPoolExecutor class is used.
        N)max_workers)_max_num_threadsEXECUTOR_CLS	_executorr   
_semaphore_tag_semaphores)r   max_sizemax_num_threadstag_semaphoresexecutor_clsr   r   r   r(     s   

zBoundedExecutor.__init__Tc                 C   sP   | j }|r
| j| }||j|}t|j|j|}t| j|}|	| |S )a1  Submit a task to complete

        :type task: s3transfer.tasks.Task
        :param task: The task to run __call__ on


        :type tag: s3transfer.futures.TaskTag
        :param tag: An optional tag to associate to the task. This
            is used to override which semaphore to use.

        :type block: boolean
        :param block: True if to wait till it is possible to submit a task.
            False, if not to wait and raise an error if not able to submit
            a task.

        :returns: The future associated to the submitted task
        )
r   r   acquirer   r   releaseExecutorFuturer   rm   ro   )r   rr   rl   block	semaphoreacquire_tokenrelease_callbackrs   r   r   r   rm     s   


zBoundedExecutor.submitc                 C   s   | j | d S r*   )r   shutdownr   rY   r   r   r   r     s   zBoundedExecutor.shutdownr3   NTT)	r   r   r   r   ThreadPoolExecutorr   r(   rm   r   r   r   r   r   r     s    

!&r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r   c                 C   r;   )a  A future returned from the executor

        Currently, it is just a wrapper around a concurrent.futures.Future.
        However, this can eventually grow to implement the needed functionality
        of concurrent.futures.Future if we move off of the library and not
        affect the rest of the codebase.

        :type future: concurrent.futures.Future
        :param future: The underlying future
        N)_futurerv   r   r   r   r(     s   
zExecutorFuture.__init__c                 C   r,   r*   )r   r   r   r   r   r   r     r-   zExecutorFuture.resultc                    s    fdd}| j | dS )a  Adds a callback to be completed once future is done

        :param fn: A callable that takes no arguments. Note that is different
            than concurrent.futures.Future.add_done_callback that requires
            a single argument for the future.
        c                    s     S r*   r   )future_passed_to_callbackfnr   r   done_callback     z7ExecutorFuture.add_done_callback.<locals>.done_callbackN)r   ro   )r   r   r   r   r   r   ro     s   
z ExecutorFuture.add_done_callbackc                 C   r,   r*   )r   r   r   r   r   r   r     r-   zExecutorFuture.doneN)r   r   r   r(   r   ro   r   r   r   r   r   r     s
    r   c                   @   s,   e Zd ZdZd
ddZdd Zddd	ZdS )BaseExecutorzABase Executor class implementation needed to work with s3transferNc                 C      d S r*   r   )r   r   r   r   r   r(        zBaseExecutor.__init__c                 O   r
   )Nzsubmit()r   )r   r   r}   r~   r   r   r   rm        zBaseExecutor.submitTc                 C   r
   )Nz
shutdown()r   r   r   r   r   r     r   zBaseExecutor.shutdownr*   r   )r   r   r   r=   r(   rm   r   r   r   r   r   r     s
    
r   c                   @   s"   e Zd ZdZdd ZdddZdS )	NonThreadedExecutorz@A drop-in replacement non-threaded version of ThreadPoolExecutorc              	   O   sj   t  }z||i |}|| W |S  ty4   t dd  \}}td||| ||| Y |S w )N   z0Setting exception for %s to %s with traceback %s)NonThreadedExecutorFuturerW   r   sysr   r\   r]   set_exception_info)r   r   r}   r~   rs   r   r/   tbr   r   r   rm     s    
zNonThreadedExecutor.submitTc                 C   r   r*   r   r   r   r   r   r   (  r   zNonThreadedExecutor.shutdownNr   )r   r   r   r=   rm   r   r   r   r   r   r     s    r   c                   @   sR   e Zd ZdZ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S )r   zThe Future returned from NonThreadedExecutor

    Note that this future is **not** thread-safe as it is being used
    from the context of a non-threaded environment.
    c                 C   s"   d | _ d | _d | _d| _g | _d S )NF)r@   rA   
_traceback_donerE   r   r   r   r   r(   3  s
   
z"NonThreadedExecutorFuture.__init__c                 C   s   || _ |   d S r*   )r@   	_set_donerV   r   r   r   rW   :  s   z$NonThreadedExecutorFuture.set_resultc                 C   s   || _ || _|   d S r*   )rA   r   r   )r   r2   	tracebackr   r   r   r   >  s   z,NonThreadedExecutorFuture.set_exception_infoNc                 C   s   | j r
| j | j| jS r*   )rA   with_tracebackr   r@   )r   timeoutr   r   r   r   C  s   z NonThreadedExecutorFuture.resultc                 C   s&   d| _ | jD ]}| | qg | _d S r   )r   rE   _invoke_done_callbackr   r   r   r   r   r   H  s   

z#NonThreadedExecutorFuture._set_donec                 C   s   || S r*   r   r   r   r   r   r   N  r   z/NonThreadedExecutorFuture._invoke_done_callbackc                 C   r)   r*   )r   r   r   r   r   r   Q  r   zNonThreadedExecutorFuture.donec                 C   s$   | j r
| | d S | j| d S r*   )r   r   rE   rz   )r   r   r   r   r   ro   T  s   z+NonThreadedExecutorFuture.add_done_callbackr*   )r   r   r   r=   r(   rW   r   r   r   r   r   ro   r   r   r   r   r   ,  s    
r   TaskTagnamein_memory_uploadin_memory_download) rQ   loggingr   rF   collectionsr   
concurrentr   s3transfer.compatr   s3transfer.exceptionsr   r   s3transfer.utilsr   r   	getLoggerr   r\   r	   r   r"   r$   r&   r   r   r   r   r   r   IN_MEMORY_UPLOAD_TAGIN_MEMORY_DOWNLOAD_TAGr   r   r   r   <module>   s0   
2' wN$/